如何在 Django 中执行 SELECT MAX?

编程入门 行业动态 更新时间:2024-10-27 22:20:24
本文介绍了如何在 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?

本文发布于:2023-10-21 17:05:05,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1514822.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何在   Django   MAX   SELECT

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!