SQLAlchemy 循环依赖 - 如何解决?
我有两个表,News
和 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'))
添加 file_id_logo
fkey 后,SQLalchemy 引发了 CircularDependencyError。 我已经在 logo
关系中尝试过 post_update=True
,但它没有改变任何东西。
解决这个问题的正确方法是什么?
可能出现以下情况(如果重要的话):
- 文件没有分配或只有一个新闻分配。
- 如果文件没有新闻,则也没有以该文件作为其徽标引用的新闻。
- 一条新闻可以有多个文件,但只有其中一个文件可以作为其
徽标
。 - 因此,如果新闻有
徽标
,则引用的文件也将此新闻作为其新闻
。
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.
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 itsnews
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
use_alter – 传递给底层ForeignKeyConstraint,指示应从CREATE TABLE/DROP TABLE 语句外部生成/删除约束。有关详细信息,请参阅该类的构造函数。
https://docs.sqlalchemy。 org/en/13/core/constraints.html#sqlalchemy.schema.ForeignKeyConstraint.params.use_alter
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.
https://docs.sqlalchemy.org/en/13/core/constraints.html#sqlalchemy.schema.ForeignKeyConstraint.params.use_alter