Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>This solution worked for me. You will need to tweak it to pass it to a template though.</p> <pre><code>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) </code></pre> <p><strong>Update</strong></p> <p>Here is one way of sending this information to the template. This one involves the use of a custom filter.</p> <pre><code>@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 </code></pre> <p>View:</p> <pre><code>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) </code></pre> <p>And in your template:</p> <pre><code>{% for country in all_countries %} &lt;h3&gt;{{ country.name }} ({{ country.story__count }})&lt;/h3&gt; {% for city in country|get_cities_and_counts %} &lt;p&gt;{{ city.name }} ({{ city.story__count }})&lt;/p&gt; {% endfor %} {% endfor %} </code></pre> <p><strong>Update 2</strong></p> <p>Variant with a custom method in model.</p> <pre><code>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) </code></pre> <p>This lets you avoid defining a filter. The template code changes to:</p> <pre><code>{% for country in all_countries %} &lt;h3&gt;{{ country.name }} ({{ country.story__count }})&lt;/h3&gt; {% for city in country.city_story_counts %} &lt;p&gt;{{ city.name }} ({{ city.story__count }})&lt;/p&gt; {% endfor %} {% endfor %} </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload