Ryan Saxe
Ryan Saxe

Reputation: 17839

Django annotation based on multiple columns

So in the docs there is the following annotation example:

Book.objects.annotate(Count('authors'))

which then allows you to do fun things like sort depending on the amount of authors. I would like to do the following:

Example.objects.annotate(value=sum('column1','column2','column5'))

now of course this does not work, but it shows what I want: to add value which is the sum of the numbers in a row that are in the first, second, and fifth column.

How can you annotate based on multiple column values in each row?

Upvotes: 0

Views: 1393

Answers (1)

Peter DeGlopper
Peter DeGlopper

Reputation: 37319

Here's how to do this with extra:

Example.objects.extra(select={'value': 'column1 + column2 + column3'})

And to filter, I believe you need to use a where clause repeating the math:

Example.objects.extra(select={'value': 'column1 + column2 + column3'},
                      where=['(column1 + column2 + column3) >= %s'],
                      params=[100])

Or whatever logic is appropriate.

Upvotes: 2

Related Questions