5

I have found a few questions that are similar to mine, but most of them are dated, or too (or too little) verbose to be helpful.

I have a model like this:

class Breakfast(models.Model):
    count_eggs = models.IntegerField()
    count_bacon = models.IntegerField()
    had_toast = models.BooleanField()

Now, in building a RESTful API, I need the ability to sort Breakfast objects by the total of count_eggs + count_bacon without storing this permanently on the model.

Many of the current and popular questions suggest something like this:

Breakfast.objects.extra(
    select={'total_food':'count_eggs + count_bacon'},
    order_by=('total_food',)
)

This seems to work for many, but Django docs appear to dissuade this solution. So, in the 1.10+ world, What is the best/correct way to do this type of filtering on the sum of two (or more) fields in Django

1
  • It might be easier to just put your addition into your order_by, but I suspect there is a better answer. Dec 11, 2017 at 17:09

2 Answers 2

5

There is a slight correction in Latrovas answers, although his query would work it unnecessary does a SUM and GROUP_BY.

The more intuitive query would be as follows:

Breakfast.objects.all().\
            annotate(total_food=F('count_eggs ') + F('count_bacon')
            ).order_by('total_food')

I'd like to go a step further and explain you how the queries work behind the scenes:

When we annotate, we're essentially adding a column in the SELECT statement of SQL. So to perform the addition of two fields we want a select statement like SELECT (eggs + bacon) as food.

This is exactly what annotate does behind the scenes.

But instead of using hardcoded values, we need to use items stored inside the database, i.e. column names like eggs and bacon expressions.

And this is exactly what F() expressions do.

Now it's a matter of time before you realise that since they do two completely different things, we can easily combine the two and use them both together for some really powerful stuff!

2
  • 1
    Excellent answer. I originally accepted @Latrova's answer, but due to the more concise nature of this code + the explanation, this will be accepted.
    – rob
    Dec 11, 2017 at 17:53
  • 1
    Thanks. I'm glad I could be of help. I've used the annotate and the more fancier stuff of django orm without really understanding how they work for a long time. So I've been doing my best to explain my findings to others ^_^ Sorry for the answer steal @Latrova hehe :)
    – oxalorg
    Dec 11, 2017 at 17:57
5

You should use annotate, I got an example of mine and adapted to your case, try this:

from django.db.models import F, Sum

Breakfast.objects.all().\
            annotate(total_food=Sum(
                F('count_eggs ') + F('count_bacon'))
            ).\
            order_by('total_food')

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.