SQLAlchemy配置表关系时报无法确定父/子表连接条件如何解决
错误原因&修复点
- 外键关联的表名写错:Password类的表名是
passwords,你在User类的ForeignKey里写的是password.password_id,少了末尾的s,改为ForeignKey('passwords.password_id')即可。 back_populates参数值对应错误:back_populates需要填写关联对方类中对应的关系属性名,你现有配置完全不匹配:- User类的
parent关系对应的是Password类的child属性,所以back_populates值应该为child - Password类的
child关系对应的是User类的parent属性,所以back_populates值应该为parent
- User类的
- 缺少DateTime类型导入:Password类中用到了
DateTime字段类型,但你没有导入该类型,需要补充导入语句。
修正后完整代码
from sqlalchemy.orm import relationship, declarative_base from sqlalchemy import Column, Integer, String, DateTime # 补充导入DateTime from sqlalchemy.sql.schema import ForeignKey Base = declarative_base() class User(Base): __tablename__ = 'users' user_id = Column(Integer, primary_key=True) name = Column(String) email = Column(String) # 修正外键关联的表名 password_id = Column(Integer, ForeignKey('passwords.password_id')) # 修正back_populates取值 parent = relationship("Password", back_populates="child") class Password(Base): __tablename__ = 'passwords' password_id = Column(Integer, primary_key=True) password = Column(String) last_change_date = Column(DateTime) valid_until = Column(DateTime) # 修正back_populates取值 child = relationship("User", back_populates="parent", uselist=False)
内容的提问来源于stack exchange,提问作者Ress
相关产品推荐
相关产品推荐

