【问题标题】:SqlAlchemy relationship many-to-many to an other many-to-manySqlAlchemy 关系多对多到另一个多对多
【发布时间】:2023-03-04 02:33:01
【问题描述】:

我有以下映射类,它是来自其他 2 个类的关联。

class InstanceCustomer(Base):
__tablename__ = 'Instances_Customers_Association'

cust_id = Column(Integer, ForeignKey('Customers.id'), primary_key=True)
inst_id = Column(Integer, ForeignKey('Instances.id'), primary_key=True)

customer = relationship(Customer, backref=backref('customer'))
instance = relationship(Instance, backref=backref('instance'))

def __init__(self, cust_id=None, inst_id=None):
    self.cust_id = cust_id
    self.inst_id = inst_id

def __repr__(self):
    return "<InstanceCustomer(cust_id='%s', inst_id='%s')>" % (self.cust_id, self.inst_id)

我想将它与 Person 类相关联。因此,由于 1 InstanceCustomer 可以有多个 Person,而 1 Person 可以有多个 Instance Customer,我将需要它们之间的其他关联,我该怎么做?主键/外键也有问题吗?

这是 Person 类

   class Person(Base):
         __tablename__ = 'person'
         id = Column( Integer, primary_key=True)

【问题讨论】:

    标签: python sqlalchemy many-to-many foreign-key-relationship composite-primary-key


    【解决方案1】:

    是N:N关系,需要交叉关系表。一个例子:

    Class A(Base):
        id = Column( Integer, primary_key=True)
    
    Class B(Base):
        id = Column( Integer, primary_key=True)
        As = relationship(
            'A',
            secondary=AnB,
            backref=backref('Bs')
        )
    
    AnB = Table(
        "table_a_to_b",
        Base.metadata,
        Column(
            'a_id',
            Integer,
            ForeignKey('A.id')
        ),
        Column(
            'b_id',
            Integer,
            ForeignKey('B.id')
        )
    )
    

    Sqlalchemy 文档供参考。

    【讨论】:

    • 感谢您的回答!我只是在挣扎,因为 InstanceCustomer 已经有两个主键,我无法处理
    • 你不需要使用这两个外键作为主键。使用自动增量 int id 作为主键。如果需要,请使用唯一键确保只有一对 (a_id, b_id)。
    • 所以如果我理解你 (a_id,b_id) 不应该是一个组合键,而应该由另一个自动递增的主键来识别。但我的问题是 InstanceCustomer 是由一个组合的主键组成的,它应该在交叉关系表中。但是当我尝试导入它们时,SQLAlchemy 抱怨:“有多个外键路径链接表等......”但即使我为关系提供了 foreign_key 参数,消息仍然存在
    猜你喜欢
    • 2021-06-26
    • 1970-01-01
    • 1970-01-01
    • 2012-06-14
    • 1970-01-01
    • 2019-11-07
    • 2018-02-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多