Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

121
Views
How do I get reverse reference in Django template?

Apologies if the title doesn't make much sense. I don't quite understand what I lack in knowledge.
I have a Post and Comment models in my Django project. What I'm trying to do is list out all the Blog posts, and show NUMBER OF COMMENTS OF EACH POST. Please see my codes below.

models.py

class Blog(models.Model):
    objects = models.Manager()
    title = models.CharField(max_length=100, blank=True)
    body = models.CharField(max_length=10000, blank=True)
    created_at = models.DateField(auto_now_add=False)

class Comment(models.Model):
    objects = models.Manager()
    post = models.ForeignKey(Blog, on_delete=models.CASCADE, related_name='comment')


views.py

def main_page(request):
    all_blogs = Blog.objects.all()
    
    context = {
        'blog' : blog,
    }
    
    return render(request, 'main/home.html', context)


template

{% for b in blog %}
<div>
    <p>{{b.title}}</p>
    <div>
        {{WHERE THE NUMBER OF THIS POST'S COMMENTS IS DISPLAYED}}
    </div>
</div>
{% endfor %}


All I need is the number of the comments, but have no idea how to do it. Is there a way to make this possible in the template? Or do I have to add some codes in views.py?

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

You can annotate the Blog objects with the number of related Comments with:

from django.db.models import Count

def main_page(request):
    all_blogs = Blog.objects.annotate(
        num_comments=Count('comment')
    )
    context = {
        'blogs' : blogs
    }
    return render(request, 'main/home.html', context)

The Blog objects that arise from that queryset will have an extra attribute .num_comments with the number of related comments:

{% for blog in blogs %}
<div>
    <p>{{ blog.title }}</p>
    <div>
        {{ blog.num_comments }}
    </div>
</div>
{% endfor %}
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!