Ryan
Ryan

Reputation: 229

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?

Upvotes: 3

Views: 211

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477180

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 %}

Upvotes: 3

Related Questions