Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/357.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Sqlalchemy一张-多张和一张表中的一张_Python_Sqlalchemy - Fatal编程技术网

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创建/删除外键约束
我不确定是什么导致了这个特殊的错误,但很可能你可以通过解决这个不明确的引用来解决它

这种模棱两可的引用是由于SQLAlchemy无法在存在多个引用(在本例中为用户和用户创建)时确定如何执行联接。这可以通过指定关系应该如何连接来解决,这可以通过指定关系应该使用的特定外键或显式确定连接条件来实现

您可以在此处看到这些应用于您的示例:

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)
有关关系联接的文档: