biw
biw

Reputation: 3085

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__ = 'parents'
    id = db.Column(Integer, primary_key=True)
    child_id = db.Column(db.Integer,db.ForeignKey("children.id", use_alter=True))
    child = db.relationship("Child",
                        uselist=False,
                        foreign_keys=[child_id],
                        post_update=True)

class Child(Base):
    __tablename__ = 'children'
    id = db.Column(db.Integer, primary_key=True)
    parent_id = db.Column(db.Integer, db.ForeignKey("parents.id"))
    user = db.relationship("Parent",
                       uselist=False,
                       foreign_keys=[parent_id])

Everything works as expected until I try to db.drop_all() and I get an error that the sqlalchemy.sql.schema.ForeignKeyConstraint name is None. Am I doing something wrong when trying to make this circular one-to-one relationship? I would really like to be able to query just the single column to get the id of the other one, hence the circular reference.

Upvotes: 4

Views: 2724

Answers (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

Upvotes: 8

Related Questions