最近在学习django的分组查询,发现使用通常的values加annotate方法,获取不到我想要的结果,后来通过查询官方文档得到答案
一、问题描述
1.1 模型
from django.db import models # Create your models here. class Goods(models.Model): g_name = models.CharField(max_length=32, help_text='商品名称') g_price = models.FloatField(help_text='商品价格') g_old_price = models.FloatField(help_text='商品原价') g_public = models.DateField(help_text='出厂日期') g_number = models.IntegerField(help_text='数量') g_store = models.CharField(max_length=32, help_text='商品产地') save_time = models.IntegerField(help_text='保质期') save_unit = models.CharField(max_length=32, help_text='保存单元') del_flag = models.CharField(max_length=32, help_text='逻辑删除') def __str__(self): return self.g_name class Meta: ordering = ['-id'] db_table = 't_goods'
查询每家店铺的生鲜种类
Goods.objects.values("g_store").annotate(total=Count("id"))
结果
<QuerySet [{'g_store': '老边生鲜', 'total': 1}, {'g_store': '老边生鲜', 'total': 1}, {'g_store': '华润万家', 'total': 1}, {'g_store': '老边生鲜', 'total': 1}, {'g_store': '沃尔玛超市', 'total': 1}, {'g_store': '永辉超市', 'total': 1}, {'g_store': '老边生鲜', 'total': 1}, {'g_store': '沃尔 玛超市', 'total': 1}, {'g_store': '老边生鲜', 'total': 1}, {'g_store': '老边生鲜', 'total': 1}, {'g_store': '老边生鲜', 'total': 1}, {'g_store': '老边生鲜', 'total': 1}, {'g_store': '华润万家', 'total': 1}, {'g_store': '沃尔玛超市', 'total': 1}, {'g_store': '华润万家', 'total': 1}, {'g_sto re': '沃尔玛超市', 'total': 1}, {'g_store': '老边生鲜', 'total': 1}, {'g_store': '华润万家', 'total': 1}, {'g_store': '老边生鲜', 'total': 1}, {' g_store': '老边生鲜', 'total': 1}, '...(remaining elements truncated)...']>
二、解决问题
2.1 解决方案
Goods.objects.order_by("g_store").values("g_store").annotate(total=Count("id"))
结果
<QuerySet [{'g_store': '华润万家', 'total': 2560}, {'g_store': '永辉超市', 'total': 2471}, {'g_store': '沃尔玛超市', 'total': 2463}, {'g_store': '老边生鲜', 'total': 2508}]>
三、官方文档
四、终极答案
Goods.objects.order_by().values("g_store").annotate(total=Count("id"))
结果
<QuerySet [{'g_store': '老边生鲜', 'total': 2508}, {'g_store': '华润万家', 'total': 2560}, {'g_store': '沃尔玛超市', 'total': 2463}, {'g_store': '永辉超市', 'total': 2471}]>
标签:help,models,text,查询,length,分组,32,Django3,store From: https://www.cnblogs.com/Durant0420/p/17472968.html