Django,找到最多2个字段的总和 [英] Django, find max of the sum of 2 fields
问题描述
class MyModel(models.Model):
fieldA = models.CharField(max_length = 100)
fieldB = models.IntegerField()
fieldC = models.IntegerField()
我想找到Max(fieldB + fieldC)。有没有Django的方式来做到这一点?或者我必须使用原始的sql(如果它会像选择最大值(fieldA + fieldB)从mymodel_table)?
提前感谢
这是一个相当迂回的解决方案,应该工作,改编自:
MyModel.objects .extra(select = {'sum':'fieldB + fieldC'})。order_by(' - sum')[0]
原始非工作答案(从Django 1.4,F()表达式在注释中不起作用)
您可以使用 F()表达式和注释/聚合进行此操作F或者你。我想你想要的是。导入F,Max
MyModel.objects.annotate(sum = F('fieldB)'
django.db.models ')+ F('fieldC'))。聚合(Max('sum'))
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
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'))
这篇关于Django,找到最多2个字段的总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!