【问题标题】:Django order by highest number of likesDjango 按点赞数排序
【发布时间】:2016-01-30 01:59:22
【问题描述】:

我正在尝试创建一个页面,人们可以在其中看到评分最高的文章,但存在一个问题:当我过滤另一位用户也喜欢的文章的点赞数时,它会创建一个被点赞文章的副本.

我想要的是按最高点赞数排序博客文章。

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 %}

为什么 Django 会多次创建同一个帖子?如何在不出现此问题的情况下按最高点赞数排序文章?

【问题讨论】:

    标签: python django


    【解决方案1】:

    Django 没有创建多个帖子。因为那个查询。 如果您想根据点赞数进行排序,那么您应该这样做,

    Article.objects.annotate(like_count=Count('likes')).order_by('-like_count')
    

    【讨论】:

      【解决方案2】:

      您需要使用annotate。以下是按“喜欢”文章的用户数量排序的方法:

      Article.objects.annotate(like_count=Count('likes')).order_by('-like_count')
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-05-17
        • 1970-01-01
        • 2023-03-24
        • 1970-01-01
        • 1970-01-01
        • 2017-08-31
        • 2020-04-22
        • 2021-09-25
        相关资源
        最近更新 更多