Skip to content Skip to sidebar Skip to footer

Sqlalchemy Circular One-to-one Relationship

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): __tablename__ = 'parent

Solution 1:

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

Post a Comment for "Sqlalchemy Circular One-to-one Relationship"