4

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

RobertoBa
  • 83
  • 1
  • 6

1 Answers1

7

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'))
Community
  • 1
  • 1
acjay
  • 34,571
  • 6
  • 57
  • 100
  • I tried what you suggested but it gives me an AttributeError -'ExpressionNode' object has no attribute 'lookup' – RobertoBa Nov 23 '12 at 10:30
  • You're right... https://code.djangoproject.com/ticket/14030. Try the solution in http://stackoverflow.com/questions/10221422/django-aggregate-queries-with-expressions. Let me know if that works, and I'll update the answer. – acjay Nov 23 '12 at 14:41