SQLAlchemy循环依赖 - 如何解决?

时间:2022-08-31 11:58:29

I have two tables, News and Files:

我有两个表,新闻和文件:

# unrelated columns removed
class News(db.Model): 
    id = db.Column(db.Integer, primary_key=True)
    file_id_logo = db.Column(db.Integer, db.ForeignKey('files.id'))
    logo = db.relationship('File', lazy=False)

class File(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    news_id = db.Column(db.Integer, db.ForeignKey('news.id'))
    news = db.relationship('News', lazy=False, backref=db.backref('files'))

After adding the file_id_logo fkey, SQLalchemy raised a CircularDependencyError. I've already tried post_update=True in the logo relation, but it did not change anything.

添加file_id_logo fkey后,SQLalchemy引发了CircularDependencyError。我已经在徽标关系中尝试了post_update = True,但它没有改变任何东西。

What's the proper way to solve this?

解决这个问题的正确方法是什么?

The following cases are possible (in case it matters):

以下情况是可能的(如果重要):

  • A File has no or exactly one News assigned.
  • 文件没有或只分配了一个新闻。
  • If a File has no News, there's also no News with this file referenced as its logo.
  • 如果文件没有新闻,则也没有此文件作为其徽标引用的新闻。
  • There can be multiple Files for a single News, but only one of these Files can be its logo.
  • 单个新闻可以有多个文件,但这些文件中只有一个可以是其徽标。
  • So if a News has a logo, the referenced File also has this news as its news.
  • 因此,如果新闻有徽标,则引用的文件也会将此新闻作为新闻。

1 个解决方案

#1


22  

use_alter – passed to the underlying ForeignKeyConstraint to indicate the constraint should be generated/dropped externally from the CREATE TABLE/ DROP TABLE statement. See that classes’ constructor for details.

use_alter - 传递给底层的ForeignKeyConstraint,指示应该从CREATE TABLE / DROP TABLE语句外部生成/删除约束。有关详细信息,请参阅该类的构造函数。

http://docs.sqlalchemy.org/en/rel_0_8/core/schema.html?highlight=use_alter#foreign-key-api-constructs

http://docs.sqlalchemy.org/en/rel_0_8/core/schema.html?highlight=use_alter#foreign-key-api-constructs

#1


22  

use_alter – passed to the underlying ForeignKeyConstraint to indicate the constraint should be generated/dropped externally from the CREATE TABLE/ DROP TABLE statement. See that classes’ constructor for details.

use_alter - 传递给底层的ForeignKeyConstraint,指示应该从CREATE TABLE / DROP TABLE语句外部生成/删除约束。有关详细信息,请参阅该类的构造函数。

http://docs.sqlalchemy.org/en/rel_0_8/core/schema.html?highlight=use_alter#foreign-key-api-constructs

http://docs.sqlalchemy.org/en/rel_0_8/core/schema.html?highlight=use_alter#foreign-key-api-constructs