Deletion of object with relationship(lazy='raise')

298 views
Skip to first unread message

Marat Sharafutdinov

unread,
Nov 22, 2019, 6:12:53 AM11/22/19
to sqlalchemy
from sqlalchemy import Column, ForeignKey, Integer, create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship, sessionmaker

Base = declarative_base()

class Parent(Base):
    __tablename__
= 'parents'
    id
= Column(Integer, primary_key=True)

class Child(Base):
    __tablename__
= 'children'
    id
= Column(Integer, primary_key=True)
    parent_id
= Column(Integer, ForeignKey(Parent.id))
    parent
= relationship(Parent, lazy='raise', passive_deletes=True)

engine
= create_engine('sqlite:///:memory:', echo=True)
Base.metadata.create_all(engine)
Session = sessionmaker(bind=engine)
session
= Session()

# Add
parent
= Parent()
session
.add(parent)
session
.flush()
child
= Child(parent_id=parent.id)
session
.add(child)
session
.commit()

# Delete
child
= session.query(Child).first()
session
.delete(child)
session
.commit()

Now I'm getting the following warning:
/.venv/lib/python3.8/site-packages/sqlalchemy/orm/relationships.py:2021: SAWarning: On Child.parent, 'passive_deletes' is normally configured on one-to-many, one-to-one, many-to-many relationships only.

If I change `parent` relationship as follows:
parent = relationship(Parent, lazy='raise', backref=backref('children', passive_deletes=True))
then I would get the following exception:
sqlalchemy.exc.InvalidRequestError: 'Child.parent' is not available due to lazy='raise'

How should it be made properly?

Mike Bayer

unread,
Nov 22, 2019, 9:22:21 AM11/22/19
to noreply-spamdigest via sqlalchemy
lazy="raise" on a many to one is problematic because a lot of many-to-one operations involve pulling up the object from the identity map, and that's it.    since people are usually only trying to guard against SQL being emitted, use the raise_on_sql option instead:

parent = relationship(Parent, lazy='raise_on_sql')

thanks for the perfect test case BTW makes this very easy for me
--
SQLAlchemy -
The Python SQL Toolkit and Object Relational Mapper
 
 
To post example code, please provide an MCVE: Minimal, Complete, and Verifiable Example. See http://stackoverflow.com/help/mcve for a full description.
---
You received this message because you are subscribed to the Google Groups "sqlalchemy" group.
To unsubscribe from this group and stop receiving emails from it, send an email to sqlalchemy+...@googlegroups.com.

Mike Bayer

unread,
Nov 22, 2019, 9:24:40 AM11/22/19
to noreply-spamdigest via sqlalchemy
that said, I'm looking at this as a potential bug because it should be able to leave this attribute alone, not really sure how this should be handled.

Mike Bayer

unread,
Nov 22, 2019, 10:09:31 AM11/22/19
to noreply-spamdigest via sqlalchemy
I can confirm this is a bug as I've found precedent for this not having to raise, new issue is
Reply all
Reply to author
Forward
0 new messages