Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7982253
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 4, 20262026-06-04T10:37:33+00:00 2026-06-04T10:37:33+00:00

I’m trying to get my head around the Discriminator on association example shipped with

  • 0

I’m trying to get my head around the “Discriminator on association” example shipped with SQLAlchemy, which defines HasAddresses mixin so each model subclassing HasAddresses magically gets an addresses attribute, which is a collection to which Address objects can be added. The linking is performed through an intermediate table so at the first glance the relationship looks like many-to-many, I hoped to be able to have multiple Addresses linked to a Customer, AND also multiple Customers and Suppliers linked to an Address.

The Address model, however, is set up in such a way that it has a single parent attribute which can only reference a single object. So, in the example, an Address can only be linked to a single Customer or Supplier.

How do I modify that example so Address is able to back-reference multiple parent objects?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-04T10:37:35+00:00Added an answer on June 4, 2026 at 10:37 am

    we can modify sqlalchemy/examples/generic_associations/table_per_association.py to add a named backref to Address, then a @property which rolls up all backrefs created.

    """table_per_association.py
    
    The HasAddresses mixin will provide a new "address_association" table for
    each parent class.   The "address" table will be shared
    for all parents.
    
    This configuration has the advantage that all Address
    rows are in one table, so that the definition of "Address"
    can be maintained in one place.   The association table 
    contains the foreign key to Address so that Address
    has no dependency on the system.
    
    
    """
    from sqlalchemy.ext.declarative import declarative_base, declared_attr
    from sqlalchemy import create_engine, Integer, Column, \
                        String, ForeignKey, Table
    from sqlalchemy.orm import Session, relationship
    import itertools
    
    class Base(object):
        """Base class which provides automated table name
        and surrogate primary key column.
    
        """
        @declared_attr
        def __tablename__(cls):
            return cls.__name__.lower()
        id = Column(Integer, primary_key=True)
    Base = declarative_base(cls=Base)
    
    class Address(Base):
        """The Address class.   
    
        This represents all address records in a 
        single table.
    
        """
        street = Column(String)
        city = Column(String)
        zip = Column(String)
    
        @property
        def all_owners(self):
            return list(
                itertools.chain(
                *[
                    getattr(self, attr)
                    for attr in [a for a in dir(self) if a.endswith("_parents")]
                ]
            ))
    
        def __repr__(self):
            return "%s(street=%r, city=%r, zip=%r)" % \
                (self.__class__.__name__, self.street, 
                self.city, self.zip)
    
    class HasAddresses(object):
        """HasAddresses mixin, creates a new address_association
        table for each parent.
    
        """
        @declared_attr
        def addresses(cls):
            address_association = Table(
                "%s_addresses" % cls.__tablename__,
                cls.metadata,
                Column("address_id", ForeignKey("address.id"), 
                                    primary_key=True),
                Column("%s_id" % cls.__tablename__, 
                                    ForeignKey("%s.id" % cls.__tablename__), 
                                    primary_key=True),
            )
            return relationship(Address, secondary=address_association, 
                        backref="%s_parents" % cls.__name__.lower())
    
    class Customer(HasAddresses, Base):
        name = Column(String)
    
    class Supplier(HasAddresses, Base):
        company_name = Column(String)
    
    engine = create_engine('sqlite://', echo=True)
    Base.metadata.create_all(engine)
    
    session = Session(engine)
    
    a1 = Address(
                street='123 anywhere street',
                city="New York",
                zip="10110")
    a2 = Address(
                street='40 main street',
                city="San Francisco",
                zip="95732")
    
    session.add_all([
        Customer(
            name='customer 1', 
            addresses=[a1, a2]
        ),
        Supplier(
            company_name="Ace Hammers",
            addresses=[a1]
        ),
    ])
    
    session.commit()
    
    for customer in session.query(Customer):
        for address in customer.addresses:
            print address.all_owners
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Basically, what I'm trying to create is a page of div tags, each has
I am trying to understand how to use SyndicationItem to display feed which is
I'm trying to select an H1 element which is the second-child in its group
I have a .ini file as follows: [playlist] numberofentries=2 File1=http://87.230.82.17:80 Title1=(#1 - 365/1400) Example
link Im having trouble converting the html entites into html characters, (&# 8217;) i
I used javascript for loading a picture on my website depending on which small
I have a string like this: La Torre Eiffel paragonata all’Everest What PHP function
I am trying to render a haml file in a javascript response like so:
I would like to run a str_replace or preg_replace which looks for certain words
I'm parsing an RSS feed that has an ’ in it. SimpleXML turns this

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.