SQLAlchemy circular one-to-one relationship

后端 未结 1 1973
没有蜡笔的小新
没有蜡笔的小新 2021-01-19 18:15

I am trying to make a circular one-to-one relationship (not sure what the correct term is) with SQLAlchemy that looks the following:

class Parent(Base):
             


        
相关标签:
1条回答
  • 2021-01-19 18:50

    From the SQLAlchemy Docs:

    class Parent(Base):
        __tablename__ = 'parent'
        id = Column(Integer, primary_key=True)
        child = relationship("Child", uselist=False, back_populates="parent")
    
    class Child(Base):
        __tablename__ = 'child'
        id = Column(Integer, primary_key=True)
        parent_id = Column(Integer, ForeignKey('parent.id'))
        parent = relationship("Parent", back_populates="child")
    

    Then you can Parent.child or Child.parent all day long

    0 讨论(0)
提交回复
热议问题