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

How do you group the values of a column and find the maximum value of a group in Django?

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

如何将此列的值计数分组并找出分组中的最大值?

我是 运行 下面的查询得到分组
Item.objects.values('item_type').annotate(total = Count('item_type')).order_by('item_type')
其中 Item 是我的模型名称。

但是,这个 returns 分组列表作为列表字典,但我需要这些分组中的最大计数。

这是通过我的 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 的值是 track-pantstotal 在这种情况下是 502

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

Item.objects.values('item_type').annotate(total = Count('item_type')).order_by('-total')[0]