I'm trying to create a page where people can see the highest rated article, there is one problem: when I filter the number of likes of an article that was also liked by another user it creates a copy of the upvoted article.
What I want is to order the articles of the blog by the highest number of likes.
models.py
class Article(models.Model):
user = models.ForeignKey(User, default='1')
[... unrelated fields ...]
likes = models.ManyToManyField(User, related_name="likes")
[... unrelated function ...]
views.py
def article_ordered_by_likes(request):
context = {'article': Article.objects.order_by('-likes')}
return render(request, 'article_ordered_by_likes.html', context)
def like_button(request):
if request.method == 'POST':
user = request.user
id = request.POST.get('pk', None)
article = get_object_or_404(Article, pk=id)
if article.likes.filter(id=user.id).exists():
article.likes.remove(user)
else:
article.likes.add(user)
context = {'likes_count': article.total_likes}
return HttpResponse(json.dumps(context), content_type='application/json')
article_ordered_by_likes.html
{% for a in article %}
[... unrelated html ...]
<h2>{{ a.titre }}</h2>
<span id="count{{ a.id }}">{{ a.total_likes }}</span>
<input type="button" class="like" id="{{ a.id }}" value="Like" />
{% endfor %}
Why is Django creating the same post multiple times? How can I order the articles by the highest number of likes without having this issue?
Django is not creating multiple posts. Its because of that query. If you want to sort based on like count then you should do like this,
Article.objects.annotate(like_count=Count('likes')).order_by('-like_count')
You will need to use annotate
. Here's how you can order by the number of users who "liked" an article:
Article.objects.annotate(like_count=Count('likes')).order_by('-like_count')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With