RobertoBa
RobertoBa

Reputation: 83

Django, find max of the sum of 2 fields

I have a model Django model like this:

class MyModel(models.Model):
  fieldA = models.CharField(max_length=100)
  fieldB = models.IntegerField()
  fieldC = models.IntegerField()

I want to find the Max(fieldB + fieldC). Is there a Django way to do this? Or do I have to go with raw sql (in case it will be something like "Select Max(fieldA + fieldB) From mymodel_table")?

Thanks in advance

Upvotes: 4

Views: 3389

Answers (1)

acjay
acjay

Reputation: 36511

Here is a rather roundabout solution that should work, adapted from Django aggregate queries with expressions:

MyModel.objects.extra(select={'sum':'fieldB + fieldC'}).order_by('-sum')[0]

Original non-working answer (as of Django 1.4, F() expressions do not work in annotations)

You can use F() expressions and annotation/aggregation to do this for you. I think what you want is.

from django.db.models import F, Max
MyModel.objects.annotate(sum=F('fieldB') + F('fieldC')).aggregate(Max('sum'))

Upvotes: 7

Related Questions