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!
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):
Very simple: