If this has to be done each time a Payment
is saved, it's better to leave that responsibility to the model instead of moving it to view. The best way is to use the post_save
signal, as something like this:
In models.py
, somewhere below the definition of the Payment
model:
from django.db.models.signals import post_save
from django.dispatch import receiver
@receiver(post_save, sender=Payment)
def my_handler(sender, instance, **kwargs):
for invoice in instance.invoice.all():
# Do some calcualtions that make us happy
invoice.save()
On an unrelated note, I strongly suggest you to use plural attribute names for M2M fields: invoices
instead of invoice
in this case. It makes it much clearer to your fellow developers.