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

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

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