Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (19.9k points)

I am trying to get the total count of occurrence of a field in same model in 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'}]>

1 Answer

0 votes
by (25.1k points)

You can get the QuerySet with:

You should make a category model like this:

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:

from django.db.models import Count

 

Category.objects.annotate(

    blog_count=Count('blog')

)

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...