sqlalchemy创建一对多关系时报错
问题描述
User表中name和phone_number组成联合主键, Express表中将User表中的联合主键设为外键,然后在Express中添加user的relationship,创建表时没有问题,但是插入一个User,
运行时报错:sqlalchemy.exc.NoForeignKeysError: Could not determine join condition between parent/child tables on relationship Express.user - 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 User(base):
__tablename__ = 'user'# id = Column(Integer)
name = Column(String(32), primary_key=True, nullable=False)
phone_number = Column(String(64), primary_key=True, nullable=False)
# express_id = relationship('Express')
class Express(base):
__tablename__ = 'express'id = Column(Integer, primary_key=True, autoincrement=True)
express_id = Column(String(64), nullable=False)
user_phone = Column(String(64))
user_name = Column(String(64))
ForeignKeyConstraint(('user_name', 'user_phone'), ['user.name', 'user.phone_number'])
user = relationship('User', backref='user_express')
base.metadata.create_all(engine)
你期待的结果是什么?实际看到的错误信息又是什么?
错误信息:
sqlalchemy.exc.NoForeignKeysError: Could not determine join condition between parent/child tables on relationship Express.user - there are no foreign keys linking these tables. Ensure that referencing columns are associated with a ForeignKey or ForeignKeyConstraint, or specify a 'primaryjoin' expression.
回答:
强烈建议,不要用强关联,弱关联既方便有又好维护
回答:
不是这个原因,请无视。
用
ForeignKeyConstraint(['user_name', 'user_phone'], ['user.name', 'user.phone_number'])
替代
ForeignKeyConstraint(('user_name', 'user_phone'), ['user.name', 'user.phone_number'])
以上是 sqlalchemy创建一对多关系时报错 的全部内容, 来源链接: utcz.com/p/937603.html