I’m trying to create a page where people can see the highest rating of an article, there is one problem: when I filter the number of articles I like that another user also likes, it creates a copy of the article above.

I want to order blog articles for the most I like.
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 record multiple times? How can I order articles on the highest numbers without this problem?
source
share