How to count and display objects in relation ManyToMany in Django

拟墨画扇 提交于 2019-11-29 22:55:30

问题


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 the website, like this:

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

How can I do this??

Thanks!


回答1:


Check out annotate() function from Django 1.1.

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

Example (from that URL above):

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



回答2:


Very simple:

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


来源:https://stackoverflow.com/questions/1773504/how-to-count-and-display-objects-in-relation-manytomany-in-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!