我如何获得在 sqlalchemy 中工作的循环关系?

how do I get a circular relation working in sqlalchemy?

我有两个实体,彼此之间存在 n:1 关系,例如:

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)

在创建表格之前,一切正常。 万一丘比特来袭,而实际上我们相互暗恋,我明白了:

>>> 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>))

我该怎么做才能让它发挥作用? (不更改表格)

好的,我明白了。 问题不在于模型定义,而在于我试图同时提交这两种关系。

这个有效:

>>> 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)
>>>