Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

130
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda