The way relationhsips interact with session.delete() seem a little obscure to me
Loading or not a relationship before session.delete() can change the behaviour of this relationship. Example:
Base = declarative_base() class Parent(Base): __tablename__ = 'Parent' name = Column(String(50)) gid = Column(Integer, primary_key = True) class Child(Base): __tablename__ = 'Child' id = Column(Integer, primary_key = True) loc = Column(String(50)) name = Column(String(50)) parent_gid = Column(Integer, ForeignKey('Parent.gid')) parent = relationship("Parent", backref=backref('children')) engine = create_engine('') session = sessionmaker() session.configure(bind=engine) s = session() Base.metadata.drop_all(engine) Base.metadata.create_all(engine) parent = Parent(name="father") child1 = Child(name="boy1") child2 = Child(name="girl1") parent.children = [child1, child2] s.add(parent) s.commit() p = s.query(Parent).one() p.children # commenting this results in l = 1, else l = 2 ch = s.query(Child).first() s.delete(ch) l = len(p.children)
I think that the first time a relationship is called, sqlalchemy makes sure to not add objects that are marked as deleted, but once the relationships has been loaded, it never checks again. Is that it ?