3

How can i get the greater of two different Decimal fields for a model using a Django query?

For example if i have a model Month with fields called income_actual and income_projected, how do i return the greater value?

I have previously used the MySQL GREATEST() function to do it but i cant work out how to do it in Django.

1
  • Will you be using the value in queries? Commented Jan 1, 2013 at 10:38

3 Answers 3

3

Have you looked into using the extra method?

Month.objects.extra(select={'max_income': 'greatest(income_actual, income_projected)'})

EDIT:

You're not going to be able to use that through the ORM without writing raw SQL. Although you could use some python magic:

sum(month['max_income'] for month in Month.objects.extra(select={'max_income': 'greatest(income_actual, income_projected)'}).values('max_income'))
Sign up to request clarification or add additional context in comments.

2 Comments

How can i then Sum max_income? If i add aggregate(Sum('max_income')) i get "Cannot resolve keyword 'max_income' into field"
Edited again. Forgot to add values() to query.
2

You may use Django's Database Function Greatest.

For example you may use such a query:

>>> from django.db.models.functions import Greatest

>>> months = Month.objects.annotate(greatest_income=Greatest('income_actual', 'income_projected').all()

# now you can access the greatest value using something like this:
>>> months[0].greatest_income

Comments

0

@drewman already gave you the version when you want to use strictly SQL. I would do things a bit differently, and add a property to the model which dynamically calculates the correct version.

class model(models.Model):
    ....

    @property
    def income(self):
        return max(self.income_actual, self.income_real)

2 Comments

Yes I've tried that but i need to Sum the income of a long list of objects and it was really slow.
Hm, right, that won't work. I think it would actually be better to just add a new column and set it to the correct value whenever one of the other two income columns are updated. That way you can use aggregation instead of complex queries, which should be both faster, and doable in ORM (at least in 1.5).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.