This solution worked for me. You will need to tweak it to pass it to a template though.
from django.db.models import Count
all_countries = Country.objects.annotate(Count('story')).order_by('-story__count')
for country in all_countries:
print "Country %s (%s)" % (country.name, country.story__count)
all_cities = City.objects.filter(country = country).annotate(Count('story')).order_by('-story__count')
for city in all_cities:
print "\tCity %s (%s)" % (city.name, city.story__count)
Update
Here is one way of sending this information to the template. This one involves the use of a custom filter.
@register.filter
def get_cities_and_counts(country):
all_cities = City.objects.filter(country = country).annotate(Count('story')).order_by('-story__count')
return all_cities
View:
def story_counts(request, *args, **kwargs):
all_countries = Country.objects.annotate(Count('story')).order_by('-story__count')
context = dict(all_countries = all_countries)
return render_to_response(..., context)
And in your template:
{% for country in all_countries %}
<h3>{{ country.name }} ({{ country.story__count }})</h3>
{% for city in country|get_cities_and_counts %}
<p>{{ city.name }} ({{ city.story__count }})</p>
{% endfor %}
{% endfor %}
Update 2
Variant with a custom method in model.
class Country(models.Model):
name = models.CharField(max_length=50)
def _get_cities_and_story_counts(self):
retrun City.objects.filter(country = self).annotate(Count('story')).order_by('-story__count')
city_story_counts = property(_get_cities_and_story_counts)
This lets you avoid defining a filter. The template code changes to:
{% for country in all_countries %}
<h3>{{ country.name }} ({{ country.story__count }})</h3>
{% for city in country.city_story_counts %}
<p>{{ city.name }} ({{ city.story__count }})</p>
{% endfor %}
{% endfor %}