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)?
You have a few solutions. Here goes, from simpler to more complex:
You could implement a custom
save
method forChildModel
that callsParentModel.save
.You could also connect to your
ChildModel
'spost_save
orpre_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 callingParentModel.save
several times, maybe without purpose.You might then want to use the following:
Override your
ParentModel
'sModelAdmin.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.