【问题标题】:SQLAlchemy many to one many times in the same table?SQLAlchemy 在同一张表中多对一多次?
【发布时间】: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_armbots_right_arm,也许你可以做类似bots = column_property(bots_left_arm+bots_right_arm)的事情,或者如果不需要在查询中使用Bit.bots.any(),只需使用hybrid_property
  • 另外,我认为您应该在Bit.bots 中使用back_populates 而不是foreign_keys

标签: python sqlalchemy


【解决方案1】:

bots = relationship("Bot", foreign_keys=[Bot.left_arm, Bot.right_arm]) 无法工作有几个原因:

  • Bot.left_armBot.right_arm 不是外键,并且
  • 即使是,foreign_keys 中的复数形式也是为了涵盖复合外键而不是复数的情况。

您可以做的是将backrefs 添加到从BitBot 的关系中:

class Bot(db.Model):
    # ...
    right_arm = relationship('Bit', foreign_keys=[right_arm_id], backref="bot_left")
    # ...
    left_arm = relationship('Bit', foreign_keys=[left_arm_id], backref="bot_right")
    # ...

class Bit(db.Model):
    # ...
    def bots(self):
        return [bot_left, bot_right]

但是,您可能会考虑使用混合属性,为此我会为您指出另一个与您的非常相似的 question: Why am I getting AmbiguousForeignKeysError?,我认为其中一个解决方案也适用于您。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-06-03
    • 1970-01-01
    • 2016-09-25
    • 1970-01-01
    • 2020-09-08
    • 2015-04-04
    • 2018-11-25
    相关资源
    最近更新 更多