1
wellsc 2018-02-23 00:54:22 +08:00
set or sql distinct
|
4
huntzhan 2018-02-23 01:28:54 +08:00
group by xxx count xxx
|
5
NaVient 2018-02-23 09:27:28 +08:00
先 xxx.objects.filter().distinct().values()将结果取为字典
再 from collections import Counter 具体用法看看文档 |
6
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/ |
7
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}) |
8
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)]> |
9
zhuyw2006 OP |