Hello!
I’m working on a Django application where I need to calculate the total of values from related objects that reference my main model with one to many relationship. These related objects can be created in two ways: either through a method in the main model, or via Django admin inlines inside the main model’s admin. I’m unsure about the best place to perform this total calculation.
Specifically:
Is it appropriate to calculate these totals in the main model’s save() method?
Is it true that related objects might be created after the main model’s save() method is called? where is the most suitable place to perform this calculation?
Thank you!
In the relational model, a normalized table definition would not store that sum as a separate field (it would be duplicated data). The typical method would be to calculate that value when needed from the related items.
It may not be optimal, but the calculation is quite heavy and i need to trigger it once the related objects are saved . While creating objects manually in the view, I can trigger it manually, but when creating related objects through inline in Django admin, is the end of save_related() method override the best place to triger it? It seems like there are no default signals when all the related objects are saved?
Correct. Basically, there is no way within Django to ensure this gets done under every condition in which those models can be updated. You would need to look at all cases individually to be certain that you have the code necessary to ensure your data remains consistent.