0

我有以下映射类,它是来自其他两个类的关联。SqlAlchemy关系多对多与其他多对多关系

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) 

回答

0

是一个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供参考。

+0

谢谢你的回答!我只是因为InstanceCustomer已经有两个主键而挣扎,我无法处理这个问题 –

+0

您不需要将这两个外键用作主键。使用自动增量int id作为主键。如果需要,使用唯一键确保只有一个(a_id,b_id)对。 – Valens

+0

所以,如果我不理解你(a_id,b_id)不应该是一个组合键,但应该由另一个主键自动增加识别。 但我的问题是,InstanceCustomer由组成的主键,它应该在交叉关系表中。但是,当我试图导入它们时,SQLAlchemy正在抱怨:“有多个外键路径链接表等,”但即使我提供了关系foreign_key参数的消息仍然存在 –