Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/281.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python SqlAlchemy关系多对多对其他多对多_Python_Sqlalchemy_Many To Many_Foreign Key Relationship_Composite Primary Key - Fatal编程技术网

Python SqlAlchemy关系多对多对其他多对多

Python SqlAlchemy关系多对多对其他多对多,python,sqlalchemy,many-to-many,foreign-key-relationship,composite-primary-key,Python,Sqlalchemy,Many To Many,Foreign Key Relationship,Composite Primary Key,我有以下映射类,它是来自其他两个类的关联 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) cus

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

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)

是一个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')
    )
)

文档供参考。

谢谢您的回答!我只是在挣扎,因为InstanceCustomer已经有了两个主键,我无法处理这一点,您不需要将这两个外键用作主键。使用自动递增的int-id作为主键。如果需要,请使用唯一密钥确保只有一对(a_id,b_id)。因此,如果我不理解,您(a_id,b_id)不应该是组合密钥,而应该由自动递增的其他主键标识。但我的问题是InstanceCustomer是由一个组合主键组成的,它应该位于交叉关系表中。但当我试图导入它们时,SQLAlchemy抱怨说:“有多个外键路径链接表等等。”但即使我为关系提供了外键参数,消息仍然存在
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')
    )
)