3

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.

1 Answer 1

3

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?

Sign up to request clarification or add additional context in comments.

2 Comments

Looks like that worked. Basically what I'm trying to do is say that the child does not belong to that parent any more. Thank you very much!
The add shouldn’t be necessary - the child is already in the session.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.