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