Skip to content Skip to sidebar Skip to footer

Does Sqlalchemy Really Have One To One Relationships

I have the following scemantic. An alert can have a status change and only one. A status change can have only one alert. A status change can have one reason also a reason can be in

Solution 1:

Perform these actions:

  • Set uselist=False on relationship
  • Set the referencing column in child unique=True
  • You can also set nullable=False on child
  • And you can add to Parent custom __init__ for strict one-to-one

Now it will work.

class Parent(Base):
    __tablename__ = 'parents'

    id = Column(Integer, primary_key=True)
    Child = relationship("Child", uselist=False, backref="Parent")

    def __init__(self,**kwargs):
        if 'Child' not in kwargs:
            raise RuntimeError('Need value')
        ...

class Child(Base):
    __tablename__ = 'childs'

    id = Column(Integer, primary_key=True)
    parent_id = Column(Integer, ForeignKey('parents.id'), unique=True)    

Base.metadata.create_all(engine)
session = Session(bind=engine)

ch1 = Child(Parent=Parent())
session.add(ch1)

p1 = Parent(Child=Child())
session.add(p1)

session.commit()

for row in session.query(Parent):
    print row.Child.id
for row in session.query(Child):
    print row.Parent.id

Post a Comment for "Does Sqlalchemy Really Have One To One Relationships"