代码
class User(Base):
__tablename__ = 'user'
id = Column(Integer, primary_key=True)
name = Column(String)
class Asset(Base):
__tablename__ = 'asset'
id = Column(Integer, primary_key=True)
user_id = Column(Integer, ForeignKey('user.id'))
user = relationship(User, foreign_keys=[user_id])
created_by = Column(Integer, ForeignKey(f"user.id"))
updated_by = Column(Integer, ForeignKey(f"user.id"))
items = db.execute(select(User).join(Asset)).all()
抛出错误:
sqlalchemy.exc.AmbiguousForeignKeysError: Can't determine join between 'user' and 'asset'; tables have more than one foreign key constraint relationship between them. Please specify the 'onclause' of this join explicitly.
解决此问题的明显方法是在语句中指定要使用哪个外键:
items = db.execute(select(User).join(Asset.user)).all()
但是有没有办法通过改变模型来解决这个问题?
我想要类似的东西:
created_by = Column(Integer, ForeignKey(f"user.id", do_not_use_for_joins=True))
updated_by = Column(Integer, ForeignKey(f"user.id", do_not_use_for_joins=True))
或者至少:
user = relationship(User, foreign_keys=[user_id], use_as_default_when_no_key_specified=True)
因为字段
created_by
和updated_by
被添加到许多表中并且已经编写了很多代码。
这可能是一个意识形态问题。在模型中不将
created_by
和 updated_by
标记为外键(而是将它们保留在数据库中)是否正常?
我已经找到解决办法了
Modifier = aliased(User)
class Asset(Base):
__tablename__ = 'asset'
id = Column(Integer, primary_key=True)
user_id = Column(Integer, ForeignKey('user.id'))
user = relationship(User, foreign_keys=[user_id])
created_by = Column(Integer, ForeignKey('Modifier.id'))
updated_by = Column(Integer, ForeignKey('Modifier.id'))
creator = relationship(Modifier, foreign_keys=[created_by], primaryjoin=created_by == Modifier.id)
updater = relationship(Modifier, foreign_keys=[updated_by], primaryjoin=updated_by == Modifier.id)