如何在 Django 中执行 SELECT MAX? [英] How to do SELECT MAX in Django?

查看:35
本文介绍了如何在 Django 中执行 SELECT MAX?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对象列表,如何运行查询以提供字段的最大值:

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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆