Vba_Beg
Vba_Beg

Reputation: 523

How to sum three columns using django ORM

I'd like to execute such query using djagno models:

SELECT id, ( first+second+third ) FROM testTable

Without grouping. Was trying to find the solution using google but unsuccessfully.

Thanks in advance,

Upvotes: 1

Views: 150

Answers (1)

olieidel
olieidel

Reputation: 1555

Use F() and annotate():

from django.db.models import F

# the sum of the three columns `first`, `second` and `third` will be
# accessible as `.my_sum`
results = my_model.objects.annotate(
                         my_sum=F('first') + F('second') + F('third'),
                       )

Upvotes: 8

Related Questions