Django trigger parent model save when editing inli

2019-06-13 15:29发布

问题:

I have a model (Parent) with one-to-many relation to another model (Child). The save method of Parent model is overwritten:

class ParentModel(models.Model)
    (...)

    def save(self, *args, **kwargs):
        (...) # Do sth with the model
        super(ParentModel, self).save(*args, **kwargs)

class ChildModel(models.Model):
    parent= models.ForeignKey(ParentModel)

In admin panel multiple Child models objects are displayed using StackedInline on Parent model's page. If a field of parent is edited and saved, the save method is called. When only child's fields are edited, Django do not call the save method of parent (as expected, because nothing changed).

What is the best way to force saving the parent, even if only child was edited (so that my overwritten method does it's stuff)?

回答1:

You have a few solutions. Here goes, from simpler to more complex:

You could implement a custom save method for ChildModel that calls ParentModel.save.
You could also connect to your ChildModel's post_save or pre_save signal.

Now, these two solutions will prove annoying if you're going to update a lot of ChildModel instances at once, as you will be calling ParentModel.save several times, maybe without purpose.
You might then want to use the following:
Override your ParentModel's ModelAdmin.change_view to handle your logic; this is pretty tricky however.

I'm however pretty surprised by the behavior your're encountering, from checking the source, the object should be saved anyway; edited or not.