Python Sqlalchemy一张-多张和一张表中的一张
我有两个模型:用户和组 用户可以在一个组中,因此:Python Sqlalchemy一张-多张和一张表中的一张,python,sqlalchemy,Python,Sqlalchemy,我有两个模型:用户和组 用户可以在一个组中,因此: class User(db.Model): # other fields group_id = db.Column(db.Integer(), db.ForeignKey('group.id')) 但另一方面,我也有一些关于创建特定组的用户的信息: class Group(db.Model): # other fields users = db.relationship("User", backref='gro
class User(db.Model):
# other fields
group_id = db.Column(db.Integer(), db.ForeignKey('group.id'))
但另一方面,我也有一些关于创建特定组的用户的信息:
class Group(db.Model):
# other fields
users = db.relationship("User", backref='group')
created_by = db.Column(db.Integer(), db.ForeignKey('user.id'))
结果是:
sqlalchemy.exc.CircularDependencyError: Can't sort tables for DROP; an unresolvable foreign key dependency exists between tables: group, user. Please ensure that the ForeignKey and ForeignKeyConstraint objects involved in the cycle have names so that they can be dropped using DROP CONSTRAINT.
我尝试了使用\u alter=True
,但它给了我:
sqlalchemy.exc.CompileError: Can't emit DROP CONSTRAINT for constraint ForeignKeyConstraint(
有趣的是,我希望您得到一个模糊的ForeignKeyError,但是您似乎得到了一个
循环依赖性错误
?据认为,这是由两种情况造成的:
- 在会话刷新操作中,如果两个对象相互依赖,则无法通过插入或删除来插入或删除它们 仅删除声明;需要更新以发布关联或 预解除其中一个外键约束值的关联。这个 在指向自身/彼此的行中描述的post_更新标志 依赖行可以解决此循环李>
- 在MetaData.sorted\u表中 操作,两个ForeignKey或ForeignKeyConstraint对象相互 相互提及。将use_alter=True标志应用于一个或两个,请参阅 通过ALTER创建/删除外键约束
class User(Base):
# Other setup / fields
group_id = Column(Integer, ForeignKey('group.id'))
class Group(Base):
# Other setup / fields
created_by_id = Column(Integer, ForeignKey('user.id'), nullable=False)
created_by = relationship("User", foreign_keys=[created_by_id])
users = relationship("User", backref="group", primaryjoin=id==User.group_id)
有关关系联接的文档: