sqlalchemy模型对象间关系配置

class Parent(Base):
    __tablename__ = 'parent'
    id = Column(Integer, primary_key=True)
    children = relationship("Child", back_populates="parent")

class Child(Base):
    __tablename__ = 'child'
    id = Column(Integer, primary_key=True)
    parent_id = Column(Integer, ForeignKey('parent.id'))
    parent = relationship("Parent", back_populates="children")


1,ForeignKey参数中是表名,非模型名, 如是一对一关系,只需要在其中一个模型中配置外键即可
  Could not determine join condition between parent/child tables on relationship User.Bonus - 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.
2,
back_populates的值一定是在对应的模型中的属性,没有就会报
'One or more mappers failed to initialize - can\'t proceed with initialization of other mappers. Triggering mapper: \'mapped class User->bp_user\'. Original exception was: Mapper \'mapped class Bonus->bp_bonus\' has no property \'User\''
3,查询时不能你中有我,我中有你,会报
'Circular reference detected'
posted on 2021-01-20 16:07  caigan  阅读(298)  评论(0编辑  收藏  举报