tags:

views:

146

answers:

2

In Django how can i return the total number of items (count) that are related to another model, e.g the way stackoverflow does a list of questions then on the side it shows the count on the answers related to that question.

This is easy if i get the questionid, i can return all answers related to that question but when am displaying the entire list of question it becomes a bit tricky to display on the side the count showing the total count.

I don't know if am clear but just think how stackoverflow displays its questions with answer,views count next to each question!

+4  A: 

QuerySet.count()

See also an example how to build QuerySets of related models.

jetxee
+1  A: 

If you're willing to use trunk, you can take advantage of the brand new annotate() QuerySet method added just a week or so ago, which solves this exact problem:

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

If you want to stick with Django 1.0, you can achieve this in a slightly less elegant way using the select argument of the extra() QuerySet method. There's an example of exactly what you are talking about using extra() here:

http://docs.djangoproject.com/en/dev/ref/models/querysets/#extra-select-none-where-none-params-none-tables-none-order-by-none-select-params-none

Finally, if you need this to be really high performance you can denormalise the count in to a separate column. I've got some examples of how to do this in the unit testing part of my presentation here:

http://www.slideshare.net/simon/advanced-django

Simon Willison