1

here is my models:

class Story(models.Model):
    writer = models.ForeignKey(UserProfile, blank=False, null=True)
    .
    .
    .

class Comment(models.Model):
    on_story = models.ForeignKey(Story, related_name="comments", blank=False, null=False)
    .
    .
    .

How do I get the number of comments related to a specific Story, and inject that into a view?

falsetru
  • 357,413
  • 63
  • 732
  • 636
Hello
  • 57
  • 6

2 Answers2

4

If you need the comment count for multiple stories, I would strongly recommend to use annotations instead of calling comments.count() on each story:

from django.db.models import Count

stories = Story.objects.order_by("-date_published").annotate(comment_count=Count('comments'))

This will reduce the number of queries from N+1 to just 1, doing the COUNT in the database using joins, instead of a separate query for each count. The count is then accessible as follows:

{% for story in stories %}
    {{ story.comment_count }}
{% endfor %}
knbk
  • 52,111
  • 9
  • 124
  • 122
-1

You can use QuerySet.count through comments attribute (related_name).

Use the following in the view function:

comment_count = specific_story.comments.count()
# do something with `comment_count`

UPDATE Use .comments.count in template:

{% for story in stories %}
    ... {{ story.comments.count }} ...
{% endfor %}
falsetru
  • 357,413
  • 63
  • 732
  • 636
  • If I implement my view like this: def index(request): story_list = Story.objects.order_by("-date_published") . . . context = {'stories': stories} return render(request, 'stories/index.html', context) How do I get the number of comments for individual stories in my template? – Hello Jan 10 '15 at 16:19
  • @Lumsum, I updated the answer after reading your comment. Please check it out. – falsetru Jan 10 '15 at 16:21
  • 2
    You could have just called comments.count in the template, actually. – Daniel Roseman Jan 10 '15 at 17:33
  • @DanielRoseman, You're right. I forgot that method call is possible in template. Thank you for pointing that. I updated the answer accordingly. – falsetru Jan 10 '15 at 17:46
  • I just asked similar question [link]:(http://stackoverflow.com/questions/31423523/django-get-count-of-photos-by-gallery-beside-gallery-name#31423628) and got similar answers. I found the annotate answer below to be faster by about 3x, not surprising as query in view is closer to db than operation in template. – curtisp Jul 15 '15 at 19:16