Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SAWarning: Object of type <Child> not in session, add operation along 'Parent.children' will not proceed

I'm stuck on this issue and I don't know how to fix it. This is my models.py file:

models.py

class TripDetail(db.Model):
    """
    Base class for every table that contains info about a trip.
    """
    __abstract__ = True
    __bind_key__ = 'instructions'

    id = db.Column(db.Integer, primary_key=True)
    # list of fields    

class Overview(TripDetail):
    """
    Class that contains general information about a trip.
    """
    __tablename__ = 'overviews'
    __table_args__ = (
        db.ForeignKeyConstraint(['user_id', 'calendar_id'], ['calendars.user_id', 'calendars.id'], ondelete='CASCADE'),
    )  # constraints on other tables, omitted here
    user_id = db.Column(db.Integer, primary_key=True)
    calendar_id = db.Column(db.Integer, primary_key=True)
    calendar = db.relationship('Calendar', backref=db.backref('overviews', cascade='delete'), passive_deletes=True)
    # other fields

class Step(TripDetail):
    __tablename__ = 'steps'

    overview_id = db.Column(db.Integer, db.ForeignKey('overviews.id', ondelete='CASCADE'))
    overview = db.relationship('Overview', backref=db.backref('steps', cascade='delete'), passive_deletes=True)
    # also other fields

And this is how I add items to the DB (the response parameter contains a dict that matches the classes, in such a way that it can be unpacked directly):

def add_instruction(response):
    """
    Adds a travel instruction to the database.
    """
    steps = response.pop('steps')
    overview = Overview(**response)
    for step in steps:
        Step(overview=overview, **step)
    db.session.add(overview)
    db.session.commit()
    logger.info(f"Stored instruction with PK {(overview.id, overview.user_id, overview.calendar_id, overview.event_id)}")

Now, the overviews table is filled up correctly, but steps stays empty. Inspecting the logs, I receive this warning:

SAWarning: Object of type not in session, add operation along 'Overview.steps' will not proceed (orm_util.state_class_str(state), operation, prop))

What am I doing wrong?

like image 366
EsotericVoid Avatar asked Sep 01 '25 05:09

EsotericVoid


1 Answers

Normally, when add()ing objects to a session, their related objects will get auto-added like you wanted. That behavior is controlled by the relationship's cascade.

Setting cascade to 'delete' in Steps.overview removes the default 'save-update', which is what turns on the auto-adding. You could just add it back with cascade='save-update, delete', but take a look at the possible traits and see what else you might need. A common set is 'all, delete-orphan'.

And remember these are strictly ORM behaviors; setting a 'delete' in your cascade won't set the column's ON [event] CASCADE.

like image 133
pentaflops Avatar answered Sep 02 '25 18:09

pentaflops