【发布时间】:2019-11-19 19:33:43
【问题描述】:
我正在尝试在 django 中获取同一模型中某个字段的出现总数。有没有可能?
例如我有一个模型如下:
class Blog(DateTimeModel):
title = models.CharField(max_length=255)
description = models.TextField()
category = models.CharField(max_length=255, null=True, blank=True)
还有一个数据表如下:
id | title | description | category
----+-------------------------------------+----------------------+----------
1 | blog title first | description 1 | social
2 | blog title second | description 2 | social
3 | blog title third | description 3 | community
4 | blog title fourth | description 4 | community
5 | blog title fifth | description 5 | people
我希望结果如下:
<QuerySet [{'category': 'social', 'blog_count': '2'}, {'category': 'community', 'blog_count': '2'}, {'category': 'people', 'blog_count': '1'}]>
我尝试过Blog.objects.values('category').order_by('category').distinct('category').count() 并得到3 的结果,这是正确的,因为它计算了与类别相关的不同值的总数。
Django annotate count with a distinct field 这篇文章提供了一个解决方案,我们可以基于两个模型计算字段。但我想要同一模型的结果。
【问题讨论】:
标签: python django django-models