首页 > 解决方案 > Django对查询集结果进行注释计数

问题描述

让我们想象下一个模型:

class Product(models.Model):
    name = models.CharField(max_lenght=255)
    category = models.ForeignKey(Category, ...)
    type = models.ForeignKey(Type, ...)
    platform = models.ForeignKey(Platform, ...)
    [...]

用户可以按每个 ForeignKey__id 字段进行过滤,过滤后的查询集用于为具有下一个结构的前端构造一个动态过滤器:

"filter": {
    "categories": [
        {
            "category__id": 1,
            "category__name": "videogames",
            "total": 12
        },
        {
            "category__id": 2,
            "category__name": "funkos",
            "total": 3
        }
    ],
    "types": [
        {
            "type__id": 3,
            "type__name": "accessory",
            "total": 2
        },
        {
            "type__id": 2,
            "type__name": "console",
            "total": 4
        }
    ]
}

其中total是与每个类别、类型等相关的产品数量。这些值的计算如下:

categories = queryset.values('category__id', 'category__name').annotate(total=Count('id'))

查询集也可以过滤,例如价格高于 25.00 美元的产品。

有没有办法根据查询集值而不是数据库值来获取总字段值(当前annotate(total=Count('id')) )?

标签: pythondjango

解决方案


推荐阅读