How to count and display objects with respect to ManyToMany in Django

I have a simple model with news and categories:

class Category(models.Model):
    name = models.CharField()
    slug = models.SlugField()

class News(models.Model):
    category = models.ManyToManyField(Category)
    title = models.CharField()
    slug = models.SlugField()
    text = models.TextField()
    date = models.DateTimeField()

I want to count news for each category and display it on a website, for example:

Sport (5)
School (4)
Films (6)
Computer (2)
etc...

How can i do this?

Thanks!

+3
source share
2 answers

Check out the annotate () function from Django 1.1.

http://docs.djangoproject.com/en/dev/topics/db/aggregation/#topics-db-aggregation

Example (from this URL above):

>>> q = Book.objects.annotate(num_authors=Count('authors'))
>>> q[0].num_authors
2
>>> q[1].num_authors
1
+7
source

Very simple:

>>> for category in Category.objects.all():
...     print category.name, category.news_set.count()
+1
source

Source: https://habr.com/ru/post/1723515/


All Articles