On Thu, Jan 22, 2009 at 10:37 PM, Gath <pgath...@gmail.com> wrote:
>
> In Django how can i return the total number of items (count) that a
> related to another model, e.g the way stackoverflow.com 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 answer count.
>
> I don't know if am clear but just think how www.stackoverflow.com
> displays its questions with answer,views count next to each question!

There are several ways you could do this:

1) Dropping to a raw SQL query is always an option. Get a database
cursor, and issue a query with the required GROUP BY to evaluate the
counts.

2) If you're using Django trunk (and soon in v1.1) you can use
annotate() to add an aggregate count to the question object:

for q in Question.objects.annotate(n_votes=Count('votes')):
    print q.text, q.n_votes

See the documentation for more details on annotate()

3) Denormalize your relations, and store the answer/view/vote count on
the question table. On a very high traffic site, this could be a
useful optimization as it lets you get your answer  without requiring
a table join.

There are a few other options, but this covers the common ones.

Yours,
Russ Magee %-)

--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to