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):
logo
.logo
, the referenced File also has this news as its news
.The Mediator Pattern can also help to lift circular dependencies by encapsulating the bidirectional interaction of two or more objects. The downside of your current code is (besides the circular dependency), that whenever class A changes and also data persistence changes, you have to touch and modify class B.
A circular dependency occurs when two classes depend on each other. For example, class A needs class B, and class B also needs class A. Circular dependencies can arise in Nest between modules and between providers. While circular dependencies should be avoided where possible, you can't always do so.
In software engineering, a circular dependency is a relation between two or more modules which either directly or indirectly depend on each other to function properly. Such modules are also known as mutually recursive.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With