drewd423
drewd423

Reputation: 351

How to remove a child from a parent in SQLAlchemy relationship

Here are my models (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 parent and a child, and relate them:

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

And all that works fine (so ignore any errors I may have made copying it to here). Now I'm trying to break the relationship, while keeping both the parent and the child in the database, and I'm coming up empty.

I appreciate any help.

Upvotes: 3

Views: 3144

Answers (1)

ACV
ACV

Reputation: 1975

I'm not sure exactly what you mean by break a relationship or why but I think this might work:

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

This post gives more info about blanking a foreign key: Can a foreign key be NULL and/or duplicate?

Upvotes: 3

Related Questions