Query by Sum from Linked Model

It was necessary here to find a discrepancy between the payment amount Payment and the amount of the PaymentItem elements associated with it.

This is solved with a simple annotation:

from django.db.models import F, Sum


Payment.objects.all()\
     .annotate(s=Sum('payment_items__amount'))\
     .exclude(amount=F('s'))

That's it.

More examples can be found in Django ORM recipes and examples.

Back to Top