![](/img/trans.png)
[英]SQLAlchemy relationship: list of objects matching either of two ForeignKey columns
[英]SQLAlchemy: Relationship with ForeignKey consisting of two columns
我将 SQLAlchemy 用于我的 Flask 应用程序,并且我希望连接两个表,其中的关系应该在两个唯一在一起的 ForeignKey 上建立。
我的第一张桌子是这样的:
class Address(db.Model):
__tablename__ = 'Address'
idx = db.Column(db.Integer, primary_key=True)
a_code1 = db.Column(db.Integer)
a_code2 = db.Column(db.Integer)
property = db.relationship('Property', backref='Address', uselist=False, lazy='select')
我的第二张表看起来像这样(p_code1 + p_code2 是唯一的 - 不是单独的)
class Property(db.Model):
__tablename__ = 'Property'
__table_args__ = (db.UniqueConstraint('p_code1', 'p_code2', name='property_id'), )
idx = db.Column(db.Integer, primary_key=True)
p_code1 = db.Column(db.Integer, db.ForeignKey('Address.a_code1'))
p_code2 = db.Column(db.Integer, db.ForeignKey('Address.a_code2'))
addresse = db.relationship('Address', backref='Property', foreign_keys=[p_code1, p_code2], uselist=False, lazy='select')
数据库正确初始化,但是,当我尝试向数据库添加内容时,出现以下错误:
sqlalchemy.exc.AmbiguousForeignKeysError: Can't determine join between 'Address' and 'Property'; tables have more than one foreign key constraint relationship between them. Please specify the 'onclause' of this join explicitly.
...
sqlalchemy.exc.AmbiguousForeignKeysError: Could not determine join condition between parent/child tables on relationship Address.property - there are multiple foreign key paths linking the tables. Specify the 'foreign_keys' argument, providing a list of those columns which should be counted as containing a foreign key reference to the parent table.
任何人都能够识别出我做错了什么吗?
p_code1
和p_code2
一起唯一的事实不是这里的问题,而是您在同一个表Property
中有两个外键指向Address
,所以 sqlalchemy 不知道如何 map 它们。
我假设您需要p_code1 = a_code1
AND p_code2 = a_code2
才能建立 map 关系。 我会明确设置primaryjoin
属性:
addresse = db.relationship(
'Address',
primaryjoin='Property.p_code1 == Address.a_code1 and Property.p_code2 == Address.a_code2',
backref='property',
uselist=False,
lazy='select'
)
如果使用backref
,则无需在 Address 中定义关系。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.