giuliocatte
giuliocatte

Reputation: 259

how do I get a circular relation working in sqlalchemy?

I have two entities with a n:1 relationship with each other, for instance:

class Boy(MyBaseModel):
    __tablename__ = 'boys'
    name = Column(String, primary_key=True)
    crush_id = Column(String, ForeignKey('girls.name'))
    crush = relationship('Girl', foreign_keys=crush_id)


class Girl(MyBaseModel):
    __tablename__ = 'girls'
    name = Column(String, primary_key=True)
    crush_id = Column(String, ForeignKey('boys.name'))
    crush = relationship('Boy', foreign_keys=crush_id)

Up to the creation of the tables, everything works fine. In the case cupid strikes, and actually we have a mutual crush, I get this:

>>> b = Boy(name='foo')
>>> g = Girl(name='bar')
>>> 
>>> b.crush = g
>>> g.crush = b
>>> 
>>> session.add(b)
>>> session.add(g)
>>> session.commit()
[...]
sqlalchemy.exc.CircularDependencyError: Circular dependency detected. (ProcessState(ManyToOneDP(Girl.crush), <Girl at 0x7f4fe719c4d0>, delete=False), ProcessState(ManyToOneDP(Boy.crush), <Boy at 0x7f4fe7759d90>, delete=False), SaveUpdateState(<Girl at 0x7f4fe719c4d0>), SaveUpdateState(<Boy at 0x7f4fe7759d90>))

what can I do to make this working? (without changing the tables)

Upvotes: 2

Views: 597

Answers (1)

giuliocatte
giuliocatte

Reputation: 259

ok I figured this out. the problem was not in the models definition, but in the fact that I was trying to commit both the relationships at once.

this works:

>>> b = Boy(name='foo')
>>> g = Girl(name='bar')
>>> b.crush = g
>>> session.add(b)
>>> session.add(g)
>>> session.commit()
>>> 
>>> g.crush = b
>>> session.commit()
>>> 
>>> b.crush
Girl(name=bar, crush_id=foo)
>>> b.crush.crush
Boy(name=foo, crush_id=bar)
>>> 

Upvotes: 1

Related Questions