Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

122
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda