Ответ 1
Это можно сделать с помощью свойств primaryjoin
и secondaryjoin
. Соответствующая документация здесь.
Пример:
customer_organization = Table(
'base_user_customer_organization', ModelBase.metadata,
Column('user_id', Integer, ForeignKey('base_user.id')),
Column('org_id', Integer, ForeignKey('base_user.id'))
)
class BaseUser(ModelBase):
__tablename__ = 'base_user'
id = Column(Integer, primary_key=True, nullable=False)
org = Column(Boolean, default=False, nullable=False)
# Shared Fields
__mapper_args__ = {
'polymorphic_on': org,
}
customers = relationship(
"BaseUser",
backref=backref('organization', order_by=id),
secondary=customer_organization,
primaryjoin=id==customer_organization.c.org_id and org==True,
secondaryjoin=id==customer_organization.c.user_id and org==False
)
class CustomerUser(BaseUser):
# Customer Fields
__mapper_args__ = {
'polymorphic_identity': False
}
class OrganizationUser(BaseUser):
# Organization Fields
__mapper_args__ = {
'polymorphic_identity': True
}
И тест:
sql = sqldb.get_session()
customer1 = sqldb.system.CustomerUser()
sql.add(customer1)
customer2 = sqldb.system.CustomerUser()
sql.add(customer2)
organization = sqldb.system.OrganizationUser()
organization.customers = [customer1, customer2]
sql.add(organization)
sql.commit()
# function prints all table data
print get_sql_table_data(sqldb.system.BaseUser)
print organization.customers
print customer1.organization
print customer2.organization
Вывод:
[{'org': False, 'id': 1}, {'org': False, 'id': 2}, {'org': True, 'id': 3}]
[<CustomerUser(id=1, org=False)>, <CustomerUser(id=2, org=False)>]
[<OrganizationUser(id=3, org=True)>]
[<OrganizationUser(id=3, org=True)>]