Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

168
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!