获取按注释值范围分组的查询集对象

Get queryset objects grouped by an annotation value range

我需要以某种方式过滤我的对象,让它们按范围分组(范围是固定的,对于这种情况,假设我们有这 3 个范围 [0.0, 33.0] [33.01, 66.0] [66.01, 100.0]

这是我的模型

class Item(models.Model):
    name = models.CharField(
        help_text="Itemname",
        max_length=256
    )
    price = models.DecimalField(max_digits=6, decimal_places=2)

我正在尝试获得如下所示的结果

{
    "0.0-33.0": [`
        {
            "name": "x"
        }
    ],
    "33.01-66.0": [
        {
            "name": "y"
        },
        {
            "name": "Z"
        }
    ]
}

我试过这样的事情:

item_by_range = Item.objects.filter(price__lte=100.0).annotate(
    price_group=Case(
        When(price__range=[0.0, 33.0], then=Value('0-33')),
        When(price__range=[33.01, 66.0], then=Value('33-66')),
        When(price__range=[66.01, 100.0], then=Value('66-100')),
        default=Value('No group'),
        output_field=CharField(),
    )
).values('name', 'price_group').order_by('price_group')

但这只有在我只传递 price_group 值时才有效,但这样我就失去了项目的名称

谢谢。

你只需要做一些 post-processinggroupby(…) [Python-doc] from the itertools module [Python-doc]:

from itertools import groupby
from operator import itemgetter

result = {
    k: [dict(name=v['name']) for v in vs]
    for k, vs in <strong>groupby(</strong>item_by_range, itemgetter('price_group')<strong>)</strong>
}

这将使字典看起来像:

{
    "0.0-33.0": [
        {"name": x}
    ],
    "33.01-66.0": [
        {"name": y},
        {"name": z}
    }
}

您不能创建多次出现相同键(此处 "name")的对象。