Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SumIf (conditional Sum) in Django ORM

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.

like image 226
Jamgreen Avatar asked Oct 26 '14 15:10

Jamgreen


2 Answers

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)))
like image 104
radoh Avatar answered Oct 17 '22 10:10

radoh


books_num_pages = Books.objects.filter(publisher__name='A', year=2014).aggregate(Sum('num_pages'))
like image 1
madzohan Avatar answered Oct 17 '22 12:10

madzohan