当前位置:  开发笔记 > 编程语言 > 正文

SQLALchemy多对多模型关系配置与多态模型

如何解决《SQLALchemy多对多模型关系配置与多态模型》经验,为你挑选了1个好方法。

因此,有一些问题和答案涉及到这个问题,但我无法将它们与我想要达到的目标完全一致.

在这里,这里和这里

我有一组自我指涉和继承的模型.这是基本设计.

class BaseUser(db.Model):
    id = db.Column(db.Integer, primary_key=True, nullable=False)
    org = db.Column(db.Boolean, default=False, nullable=False)
    # Shared Fields
    __mapper_args__ = {
        'polymorphic_on': org,
    }

class Customer(BaseUser):
    # Customer Fields
    __mapper_args__ = {
        'polymorphic_identity': 0
    }

class Organization(BaseUser):
    # Organization Fields
    __mapper_args__ = {
        'polymorphic_identity': 1
    }

class CustomerOrganization(db.Model):
    user_id = db.Column(db.ForeignKey('customer.id', ondelete=CASCADE, onupdate=CASCADE), primary_key=True, nullable=False)
    org_id = db.Column(db.ForeignKey('customer.id', ondelete=CASCADE, onupdate=CASCADE), primary_key=True, nullable=False)

我尝试了几种不同的方法来为这些类型中的每一种创建"组织"和"成员"关系.有关如何定义relationsihp()属性的任何建议?



1> Boris Serebr..:

它可以使用primaryjoinsecondaryjoin属性完成.相关文档在这里.

例:

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}]
[, ]
[]
[]

推荐阅读
黄晓敏3023
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有