python - 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')) )?
解决方案
推荐阅读
- java - Apache Ignite 嵌入式集群模式
- terraform - 字符串列表的 Terraform 可选参数
- windows - 运行基于 GEANT4 的示例应用程序时出错。“指定的会话类型未在您的系统中构建,或未指定会话类型
- python - 如何降低 PySpark 中 ArrayType 或 MapType 列中元素名称的大小写?
- performance - jmeter.properties 和 jmeter-server 文件中需要什么更新来创建 JMeter 远程负载测试
- reactjs - 错误:对象作为 React 子级无效如果您打算渲染一组子级,请改用数组我不确定我哪里出错
- javascript - 使用javascript自动提交表单仍然需要交互才能完成
- reactjs - 如何使 Bootstrap 表的复选框具有响应性
- jwt - laravel 8 JWT ErrorException:试图获取非对象的属性“id”
- windows - Spark结构化流式writeStream到控制台问题