Reputation: 83
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
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