Relationship and session.delete

Issue #3683 invalid
Mehdi Gmira 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()
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 ?

Comments (1)

  1. Mike Bayer repo owner

    this is a support request (because it's a question). please refer to the community guide at http://www.sqlalchemy.org/support.html 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 http://docs.sqlalchemy.org/en/rel_1_0/orm/session_basics.html#deleting-from-collections.

  2. Log in to comment