Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django SUM Query?

I have a query akin to the following:

SELECT SUM(ISNULL(table.name)) FROM table 

How does that SUM translate into a QuerySet in Django? i.e. What operation xyz does it translate to, in something like MyModel.objects.xyz()?

like image 723
user541686 Avatar asked Jun 26 '11 00:06

user541686


People also ask

How does Django calculate average?

You simply using values() , aggregate() and function Avg() and F() .

What does aggregate do in Django?

When specifying the field to be aggregated in an aggregate function, Django will allow you to use the same double underscore notation that is used when referring to related fields in filters. Django will then handle any table joins that are required to retrieve and aggregate the related value.

What is F in Django Queryset?

In the Django QuerySet API, F() expressions are used to refer to model field values directly in the database.


1 Answers

Update: The following incorporates the ISNULL aspect of the original query:

from django.db.models import Sum  ModelName.objects.filter(field_name__isnull=True).aggregate(Sum('field_name')) # returns {'field_name__sum': 1000} for example 

You're looking for the Sum aggregation function, which works as follows:

ModelName.objects.aggregate(Sum('field_name')) 

See: https://docs.djangoproject.com/en/dev/ref/models/querysets/#sum

like image 190
rolling stone Avatar answered Oct 02 '22 18:10

rolling stone