如何计算和显示Django中ManyToMany关系中的对象

时间:2009-11-20 21:57:48

标签: python django django-models many-to-many

我有一个包含新闻和类别的简单模型:

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()

我想计算每个类别的新闻并将其显示在网站上,如下所示:

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

我该怎么做?

谢谢!

2 个答案:

答案 0 :(得分:7)

从Django 1.1中查看annotate()函数。

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

示例(来自上面的URL):

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

答案 1 :(得分:1)

很简单:

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