Add "post save" hook to ModelAdmin class
|Reported by:||3point2||Owned by:||pandres|
|Has patch:||yes||Needs documentation:||yes|
|Needs tests:||yes||Patch needs improvement:||yes|
If a model with a set of related objects is edited in the admin, there is currently no way to run any code once the admin site has saved the related objects.
For example, consider an invoice:
class Invoice(models.Model): # fields like customer_name, etc total = models.DecimalField(max_digits=11, decimal_places=2) def update_total(self): self.total = sum([x.cost for x in self.invoiceentry_set.all()] class InvoiceEntry(models.Model): invoice = models.ForeignKey(Invoice) item = models.CharField(max_length=100) cost = models.DecimalField(max_digits=11, decimal_places=2) # etc
When clicking "save" in the admin after editing or adding an invoice in the admin interface, there is no way to have the invoice update its total using the update_total method. Overriding the save() method on the Invoice model doesn't help, because it is called before the related InvoiceEntries are created and saved.
I supposes the functionality I want could be implemented by overriding the save() method for the InvoiceEntry model and have it update the total of the parent instance, although this seems a little inelegant as the Invoice instance would then be updated and saved once for every invoice entry created or edited.
I suggest adding a "post_save" option to the ModelAdmin class, which will be called once all related objects have been saved. Please consider the attached patch. It allows the following:
class InvoiceAdmin(admin.ModelAdmin): def post_save(self, instance): instance.update_total() admin.site.register(Invoice, InvoiceAdmin)
With the patch, the post_save method above is called after the invoice and all its related entries have been created and saved.
If this is considered for inclusion into Django, I'd be happy to modify the patch to include documentation.
Change History (6)
comment:1 Changed 6 years ago by
|Owner:||changed from nobody to pandres|
|Patch needs improvement:||unset|
comment:2 Changed 6 years ago by
|Patch needs improvement:||set|
|Status:||new → closed|