Cascade child updates onto the parent

988 views
Skip to first unread message

Colton Allen

unread,
May 27, 2020, 3:57:18 PM5/27/20
to sqlalchemy
Hello,

I'm trying to automate a backref update.  Basically, when a child model is inserted or updated I want the parent model's "updated_at" column to mutate.  The value should be the approximate time the user-child-model was updated.  The updated_at value would not have to match the created_at/updated_at value on the child.  It would just need to mutate to a new time.

class UserModel(db.Model):
    updated_at
= db.Column(db.DateTime, default=db.now, onupdate=datetime.now)


class UserChildModel(db.Model):
    user_id
= db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
    user
= db.relationship('UserModel', backref='children')

user
= UserModel()
save
(user)
print(user.updated_at) # x

child
= UserChildModel(user_id=user.id)
save
(child)
print(user.updated_at) # y (value changed)

Hopefully this pseudocode is sufficient.

I'm wondering if there is an option I can specify on the orm.relationship factory.  Or will I need to define an event?

Thanks!

Mike Bayer

unread,
May 28, 2020, 12:06:28 PM5/28/20
to noreply-spamdigest via sqlalchemy
that could certainly be based on an event from the SQLAlchemy side.     a very straightforward one would be the before_insert / before_update / after_insert / after_update suite of events, I would emit an UPDATE statement against the parent table using the foreign key on the child row that's being inserted/updated.      Another approach would be a DB trigger.


the "connection" right there is where you'd run your update, like:

connection.execute(update(parent).values(updated_at=datetime.now()).where(parent.id == inserted.parent_id))





Thanks!


--
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.

Colton Allen

unread,
May 28, 2020, 1:12:25 PM5/28/20
to sqlalchemy
Perfect.  That's exactly what I ended up doing.  I added events (after_insert/update/delete) for each backref.

For each has-many relationship (through a secondary table) I had to consider the fact that the parent model would exist in session.dirty but not trigger the "onupdate" action on the column.  So I added a generic before_update/delete event on my models' base class which is basically just target.updated_at = dt.now().
To unsubscribe from this group and stop receiving emails from it, send an email to sqlal...@googlegroups.com.
Reply all
Reply to author
Forward
0 new messages