Reputation: 382
I see in the docs the aggregate and annotate functions can be used to create a new column in the query, so if I write something like:
my_object = ...objects.filter(something).annotate(extra_column=Avg(value))
the inner query will give an extra column
, AVG(value) AS "extra_column" ...
Now, it seems to me that it can be used only will functions like count, avg, max, and min... can I do something as a simple +/- certain number?
I'm trying .annotate(extra_column=another_column+1)
or .annotate(extra_column='another_column'+1)
but it doesn't work.
What am I doing wrong? Sorry for the silly question.
Upvotes: 0
Views: 678
Reputation: 3364
You'd use F()
expressions for arithmetic. F()
is part of query expressions. From the documentation:
Django supports addition, subtraction, multiplication, division, modulo arithmetic, and the power operator on query expressions, using Python constants, variables, and even other expressions.
A code example is:
from django.db.models import F
my_object = Model.objects.annotate(extra_column=F('another_column') + 1)
my_object = Model.objects.annotate(extra_column=F('another_column') * F('yet_another_column'))
Upvotes: 2
Reputation: 1579
The aggregate functions do return the integer which could be manipulated by adding, subtracting etc.
The following example works on Django 1.11.6:
from django.db.models import Count
employees = Employee.objects.annotate(managers=Count('manager') + 10) # every employee has only a single manager.
print employees[0].managers # prints out 11
Upvotes: 0