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.