Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django order by highest number of likes

Tags:

python

django

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.

enter image description here

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?

like image 334
Hiroyuki Nuri Avatar asked Jan 30 '16 01:01

Hiroyuki Nuri


Video Answer


2 Answers

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')
like image 121
Anoop Avatar answered Sep 18 '22 04:09

Anoop


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')
like image 26
Derek Kwok Avatar answered Sep 18 '22 04:09

Derek Kwok