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

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

问题描述

我有一个对象列表,我可以如何运行查询来给出一个字段的最大值:



我使用这段代码:

  def get_best_argument(self):
try:
arg = self.argument_set.order_by(' - rating')[ 0] .details
除了IndexError:
返回'没有帖子'
返回arg

评分是一个整数

解决方案

请参阅这个。您的代码将如下所示:

  from django.db.models import Max 
#生成一个SELECT MAX ...语句
Argument.objects.all()。aggregate(Max('rating'))

如果您已经从数据库中获取了列表,那么您可以执行以下操作:

  from django.db.models import Max 
args = Argument.objects.all()
#计算已经检索到的对象中的最大值
args.aggregate(Max('rating '))

这是未经测试的,所以我可能在某个地方犯了一个错误,但是你走了。 / p>

I have a list of objects how can I run a query to give the max value of a field:

I'm using this code:

def get_best_argument(self):
    try:
        arg = self.argument_set.order_by('-rating')[0].details
    except IndexError:
        return 'no posts'
    return arg

rating is an integer

解决方案

See this. Your code would be something like the following:

from django.db.models import Max
# Generates a "SELECT MAX..." statement
Argument.objects.all().aggregate(Max('rating'))

If you've already gotten the list out of the database, then you'd do something like this:

from django.db.models import Max
args = Argument.objects.all()
# Calculates the maximum out of the already-retrieved objects
args.aggregate(Max('rating'))

This is untested so I may have made a mistake somewhere, but there you go.

这篇关于在Django中如何做SELECT MAX?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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