新手求助, Django 去重并统计数量的问题!

2018-02-23 00:50:08 +08:00
 zhuyw2006
数据库全部读取,显示都没问题,怎么把重复的合并.,并在他们每个后面统计出数量。数据库里面就一列,里面有很多重复名称。
5880 次点击
所在节点    Python
10 条回复
wellsc
2018-02-23 00:54:22 +08:00
set or sql distinct
zhuyw2006
2018-02-23 01:18:02 +08:00
@wellsc 去除重复是没问题,就是不知道如何统计显示出每个名称重复的数量
Comphuse
2018-02-23 01:28:02 +08:00
@zhuyw2006 import collections.Counter
huntzhan
2018-02-23 01:28:54 +08:00
group by xxx count xxx
NaVient
2018-02-23 09:27:28 +08:00
先 xxx.objects.filter().distinct().values()将结果取为字典
再 from collections import Counter 具体用法看看文档
wizardoz
2018-02-23 09:51:20 +08:00
楼主要的是不是这种?
>>> from django.db.models import Count
>>> pubs = Publisher.objects.annotate(num_books=Count('book'))
>>> pubs
<QuerySet [<Publisher: BaloneyPress>, <Publisher: SalamiPress>, ...]>
>>> pubs[0].num_books
73


https://docs.djangoproject.com/en/2.0/topics/db/aggregation/
xpresslink
2018-02-23 23:37:16 +08:00
假设有这样一个只有一字段的 Model
class MyModel(models.Model):
□□□□item = models.CharField(max_length=100)
□□□□def __str__(self):s
□□□□□□□□return self.item
□□□□class Meta:
□□□□□□□□verbose_name = 'MM'

>>> from temp.models import MyModel as MM
MM.objects.values_list('item', flat=True)
<QuerySet ['a', 'b', 'c', 'd', 'e', 'a', 'a', 'e', 'b', 'b', 'b', 'b', 'f', 'a', 'c', 'b']>
>>> from django.db.models import Count
>>> MM.objects.values_list('item', flat=True).annotate(Count('item'))
<QuerySet ['c', 2, 'b', 6, 'a', 4, 'f', 1, 'e', 2, 'd', 1]>

>>> from collections import Counter
>>> Counter(MM.objects.values_list('item', flat=True))
Counter({'b': 6, 'a': 4, 'c': 2, 'e': 2, 'd': 1, 'f': 1})
xpresslink
2018-02-23 23:40:02 +08:00
>>> MM.objects.values_list('item').annotate(Count('item'))
<QuerySet [('c', 2), ('b', 6), ('a', 4), ('f', 1), ('e', 2), ('d', 1)]>
zhuyw2006
2018-02-24 16:39:54 +08:00
@Comphuse
@huntzhan
@NaVient
@wizardoz
@xpresslink 谢谢🙏,已经安装这样搞定了
chengxiao
2018-02-28 11:28:56 +08:00
@zhuyw2006 怎么搞定的 能给一下思路吗?

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/431789

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX