[英]SqlAlchemy relationship many-to-many to an other many-to-many
我有以下映射的類,它是來自其他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)
我想將其與班級人員聯系起來。 因此,由於1個InstanceCustomer可以有很多人,而1個人可以有許多實例客戶,我將需要它們之間的其他關聯,我該怎么做? 主鍵/外鍵也有問題嗎?
這是班人
class Person(Base):
__tablename__ = 'person'
id = Column( Integer, primary_key=True)
是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 doc供參考。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.