17

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 its news.
ThiefMaster
  • 310,957
  • 84
  • 592
  • 636

1 Answers1

24

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

Sean
  • 2,632
  • 2
  • 27
  • 35
sector119
  • 888
  • 8
  • 12
  • Worked fine to get rid of the error, but it broke some other relationships. So I decided to simply get rid of the ForeignKey. Accepting it anyway since the answer itself is correct. – ThiefMaster Apr 30 '11 at 19:32
  • 3
    @ThiefMaster You probably just needed to set primaryjoin on your relation - they cannot determine join direction when there's multiple relations/backrefs between two tables. – thule May 07 '11 at 09:37
  • 1
    I found the information here: http://docs.sqlalchemy.org/en/rel_0_8/core/constraints.html – David C Oct 10 '15 at 20:07