I have two models: Publisher and Book.
I am retrieving publishers with
Publisher.objects.filter(name="A").annotate(total_pages=Sum('books__num_pages'))
but I am only interested in the total sum of number of pages for books written in 2014.
I am not familiar with any options to make a SUMIF in Django. How does others solve this problem?
I think there should be some possibility to do something like
Sum('books__num_pages', where={'year': 2014})
or something like that.
You were very close to actual proper solution (or maybe django didn't have it back in 2014?), Sum
function has a filter
parameter, so you can do:
from django.db.models import Sum, Q
...
Publisher.objects.filter(name="A").annotate(total_pages=Sum('books__num_pages', filter=Q(year=2014)))
books_num_pages = Books.objects.filter(publisher__name='A', year=2014).aggregate(Sum('num_pages'))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With