我有一个对象列表,如何运行查询以提供字段的最大值:
I have a list of objects how can I run a query to give the max value of a field:
我正在使用此代码:
def get_best_argument(self): try: arg = self.argument_set.order_by('-rating')[0].details except IndexError: return 'no posts' return arg评级是一个整数
推荐答案参见 这个.您的代码将类似于以下内容:
See this. Your code would be something like the following:
from django.db.models import Max # Generates a "SELECT MAX..." query Argument.objects.aggregate(Max('rating')) # {'rating__max': 5}您也可以在现有查询集上使用它:
You can also use this on existing querysets:
from django.db.models import Max args = Argument.objects.filter(name='foo') # or whatever arbitrary queryset args.aggregate(Max('rating')) # {'rating__max': 5}如果您需要包含此最大值的模型实例,那么您发布的代码可能是最好的方法:
If you need the model instance that contains this max value, then the code you posted is probably the best way to do it:
arg = args.order_by('-rating')[0]请注意,如果查询集为空,即如果没有参数与查询匹配,则会出错(因为 [0] 部分将引发 IndexError).如果您想避免这种行为,而是在这种情况下简单地返回 None,请使用 .first():
Note that this will error if the queryset is empty, i.e. if no arguments match the query (because the [0] part will raise an IndexError). If you want to avoid that behavior and instead simply return None in that case, use .first():
arg = args.order_by('-rating').first() # may return None更多推荐
如何在 Django 中执行 SELECT MAX?
发布评论