[Fixed]-Related models update on model field change

1👍

Overriding save() will work:

class ActivityObject(models.Model):
    is_deleted = models.BooleanField(default=False)

    def save(self, *args, **kwargs):
        super(ActivityObject, self).save(args, kwargs)
        if self.is_deleted:
            for job in self.activity_jobs:
                job.is_deleted = True
                job.save()

Just guessing here, but if the real purpose of this is to delete ActivityJobs when related ActivityObjects are deleted, then you can just go ahead and delete the ActivityObject. Django’s default behavior will remove all the ActivityJobs connected to it.

If you want to perform some other action when deleting, use Django’s pre_delete or post_delete signals, which will call a function you define before/after deleting objects of the type you specify.

EDIT: if you ever use update() on querysets dealing with ActivityObject and changing is_deleted, you can either ensure that you perform a corresponding update() on ActivityJob, or you can override ActivityObject‘s queryset functionality like this to make it happen automatically.

0👍

You can use Django signals’ pre_delete or post_delete. More details and examples are available in the Django Signals documentation.

Leave a comment