如何对列的值进行分组并在Django中查找组的最大值?

问题描述 投票:0回答:1

假设我有一个名为item_type的列,其中包含牛仔裤,裤子,T恤等值。

如何对此列的值计数进行分组并查找组中的最大值?

我正在运行以下查询获取分组 Item.objects.values('item_type').annotate(total = Count('item_type')).order_by('item_type') 其中Item是我的型号名称。

但是,这会将分组列表作为列表字典返回,但我需要这些分组中的最大计数。

这是通过我的HTML模板返回的内容:

{'item_type': 'jeans', 'total': 250}
{'item_type': 'shirts', 'total': 350}
{'item_type': 'track-pants', 'total': 502}
{'item_type': 'trousers', 'total': 136}
{'item_type': 'tshirts', 'total': 450}

我如何检索这个:{'item_type':'track-pants','total':502}

那么,有没有办法将最大值提取为变量?基本上我想要的是关键item_type的值,它是跟踪裤子,相同的总数是502,在这种情况下是502。

django django-models django-queryset django-orm
1个回答
1
投票

您可以在order_by语句中使用带注释的总计。您可以按计数订购并获得第一项,如下所示:

Item.objects.values('item_type').annotate(total = Count('item_type')).order_by('-total')[0]
© www.soinside.com 2019 - 2024. All rights reserved.