Relationship and session.delete

Issue #3683 invalid
created an issue

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()
s = session()


parent = Parent(name="father")
child1 = Child(name="boy1")
child2 = Child(name="girl1")
parent.children = [child1, child2]



p = s.query(Parent).one()
p.children  # commenting this results in l = 1, else l = 2
ch = s.query(Child).first()
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 ?

Comments (1)

  1. Michael Bayer repo owner

    this is a support request (because it's a question). please refer to the community guide at for guidelines on how to get support. thanks!

    The behavior here is a combination of autoflush occurring before you grab that collection, and working with collection deletion most effectively is described in the documentation at

  2. Log in to comment