Python – How to remove a child from a parent in a SQLAlchemy relationship

How to remove a child from a parent in a SQLAlchemy relationship… here is a solution to the problem.

How to remove a child from a parent in a SQLAlchemy relationship

Here is my model (ignoring imports):

class Parent(Base):
    __tablename__ = 'parents'
    id = Column(Integer, primary_key=True)
    name = Column(String)
    children = relationship('Child', backref='parent', lazy='dynamic')

class Child(Base):
    __tablename__ = 'children'
    id = Column(Integer, primary_key=True)
    name = Column(String)
    parent_id = Column(Integer, ForeignKey('parents.id'))

Next I create a father and son and associate them:

dbsession = session()
child = Child(name='bar')
dbsession.add(child)
parent = Parent(name='foo')
parent.children.append(child)
dbsession.add(parent)
dbsession.commit()

Everything works fine (so ignore any errors I might have when I copied it here). Now I tried to break the relationship and save both the parent and child in the database at the same time, but the result is empty.

Thanks for any help.

Solution

I’m not sure exactly what you mean or why you mean by breaking relationships, but I think it might work :

child = dbsession.query(Child).filter(Child.name=='bar').one()
child.parent_id = None
dbsession.add(child)
dbsession.commit()

This article provides more information about blank foreign keys: Can a foreign key be NULL and/or duplicate?

Related Problems and Solutions