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

170
Visualizações
template tag is showing duplicate items in template

I am building a Blog App and I built a template tag to sort posts by likes. Template tag I working fine, But when I sort by likes then it is showing duplicate items according to likes. I mean, If a post got 3 likes then it is showing that post thee times.

models.py

class BlogPost(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    title = models.CharField(max_length=1000)
    body = models.CharField(max_length=1000)
    likes = models.ManyToManyField(User, related_name='likes')

template_tags.py

from django import template

register = template.Library()

@register.filter
def sort(queryset, order):
    return queryset.order_by(order)

views.py

def posts(request):
    posts = BlogPost.objects.filter(user=request.user)

    context = {'posts':posts}
    return render(request, 'posts.html', context)

posts.html


{% load template_tags %}

{% block content %}


{% for post in posts|sort:'likes' %}

{{post.title}}

{% endfor %}


{% endblock content %}

I have also tried by using distinct() in both template_tags.py and views.py but it is making no effect on query.

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

The following should work to get the ordering you want from the view

from django.db.models import Count


def posts(request):
    posts = BlogPost.objects.filter(
        user=request.user
    ).annotate(
        count_likes=Count('likes')
    ).order_by('count_likes').distinct()

    context = {'posts':posts}
    return render(request, 'posts.html', context)

Your sort filter is not useful when you need to sort by an annotation. I'm not sure the filter is useful at all, the ordering should be done in the view

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