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})