我有一个对象列表,如何运行查询来给出字段的最大值:
我正在使用这段代码:
def get_best_argument(self):
try:
arg = self.argument_set.order_by('-rating')[0].details
except IndexError:
return 'no posts'
return arg
评级是一个整数
See this http://docs.djangoproject.com/en/dev/topics/db/aggregation/。您的代码将类似于以下内容:
from django.db.models import Max
# Generates a "SELECT MAX..." query
Argument.objects.aggregate(Max('rating')) # {'rating__max': 5}
您还可以在现有查询集上使用它:
from django.db.models import Max
args = Argument.objects.filter(name='foo') # or whatever arbitrary queryset
args.aggregate(Max('rating')) # {'rating__max': 5}
如果您需要包含此最大值的模型实例,那么您发布的代码可能是最好的方法:
arg = args.order_by('-rating')[0]
请注意,如果查询集为空,即如果没有参数与查询匹配,这将出错(因为[0]
部分将提出IndexError
)。如果您想避免这种行为而只是返回None
在这种情况下,使用.first() https://docs.djangoproject.com/en/dev/ref/models/querysets/#first:
arg = args.order_by('-rating').first() # may return None
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)