简体   繁体   English

如何计算Django中相同模型的不同字段的总出现次数?

[英]How to count total occurrence of distinct field of same model in django?

I am trying to get the total count of occurrence of a field in same model in django. 我正在尝试在django中获取同一模型中某个字段发生的总数。 Is it possible to do it or not? 有可能做到吗?

for example I have a model as below: 例如我有一个如下模型:

class Blog(DateTimeModel):
    title = models.CharField(max_length=255)
    description = models.TextField()
    category = models.CharField(max_length=255, null=True, blank=True)

and a table of data as below: 数据表如下:

 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

I want a result to be as: 我希望结果是:

<QuerySet [{'category': 'social', 'blog_count': '2'}, {'category': 'community', 'blog_count': '2'}, {'category': 'people', 'blog_count': '1'}]>

I have tried doing Blog.objects.values('category').order_by('category').distinct('category').count() and got result as 3 which is true because it had count the total distinct values related to category. 我尝试做Blog.objects.values('category').order_by('category').distinct('category').count()并得到结果为3 ,这是正确的,因为它已经计算了与类别。

Django annotate count with a distinct field this post provide a solution where we can count fields based on two models. Django使用不同的字段注释计数,本文提供了一种解决方案,其中我们可以基于两个模型对字段进行计数。 But i want the results from the same model. 但是我想要来自同一模型的结果。

You can obtain such queryset with: 您可以通过以下方式获取此类查询集:

from django.db.models import Count

Blog.objects.values('category').annotate(
    blog_count=Count('pk')
).order_by('category')

That being said, the modeling might not be optimal, since it creates a lot of data duplication . 话虽如此,建模可能不是最佳的,因为它会创建大量数据重复 Imagine if you later want to rename a category , then this would result in a huge amount of work, since these categories can be spread over a lot of tables. 想象一下,如果您以后要重命名一个category ,那么这将导致大量的工作,因为这些类别可以分布在很多表上。

It makes more sense to then implement a Category model, like: 然后实现Category模型更有意义,例如:

class Category(models.Model):
    name = models.CharField(max_length=255, unique=True)

class Blog(DateTimeModel):
    title = models.CharField(max_length=255)
    description = models.TextField()
    category = models.ForeignKey(Category, null=True)

Then you can annotate the Category objects, like: 然后,您可以注释Category对象,例如:

from django.db.models import Count

Category.objects.annotate(
    blog_count=Count('blog')
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM