【发布时间】:2021-04-07 02:58:46
【问题描述】:
我有“Bot”和“Bit”类,每个 Bot 都将由多个位组成(现在只有左右臂)。我想通过在表本身中引用机器人包含的每个位来做到这一点,因此不需要关联表,因为每个机器人都将具有相同数量和类型的位。
但是,我也希望能够获取具有特定位的所有机器人,并认为我可以将机器人作为父级返回到位,但随后我收到此错误:
Could not determine join condition between parent/child tables on relationship Bit.bots - 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.
我尝试将foreign_keys=[Bot.left_arm, Bot.right_arm] 添加到机器人关系中,但这只是将错误更改为:
Could not determine join condition between parent/child tables on relationship Bit.bots - there are no foreign keys linking these tables. Ensure that referencing columns are associated with a ForeignKey or ForeignKeyConstraint, or specify a 'primaryjoin' expression.
以下是我目前的课程:
class Bot(db.Model):
id = db.Column(db.Integer, primary_key=True)
level = db.Column(db.Integer, default=1)
right_arm_id = db.Column(db.Integer, ForeignKey('bit.id'))
right_arm = relationship('Bit', foreign_keys=[right_arm_id])
left_arm_id = db.Column(db.Integer, ForeignKey('bit.id'))
left_arm = relationship('Bit', foreign_keys=[left_arm_id])
image_file = db.Column(db.String(30))
class Bit(db.Model):
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
part = db.Column(db.Integer)
category_id = db.Column(db.Integer, db.ForeignKey('category.id'))
category = relationship('Category')
name = db.Column(db.String(30))
coordinate = db.Column(db.String(16))
image_file = db.Column(db.String(30))
bots = relationship("Bot", foreign_keys=[Bot.left_arm, Bot.right_arm])
非常感谢任何有关如何修复它或更好的方法的想法!
【问题讨论】:
-
这只是我的一个想法,可能根本行不通,但如果你有
bots_left_arm和bots_right_arm,也许你可以做类似bots = column_property(bots_left_arm+bots_right_arm)的事情,或者如果不需要在查询中使用Bit.bots.any(),只需使用hybrid_property。 -
另外,我认为您应该在
Bit.bots中使用back_populates而不是foreign_keys。
标签: python sqlalchemy