【问题标题】:Django - How to sort Post model by votes?Django - 如何通过投票对 Post 模型进行排序?
【发布时间】:2021-04-15 07:23:10
【问题描述】:

我正在尝试对views.py中的帖子进行排序,从顶部到底部的投票数最多。

这是我目前所拥有的:

在models.py中发布模型

class Post(models.Model):
    title = models.CharField("HeadLine", max_length=256, unique=True)
    creator = models.ForeignKey(User, on_delete= models.SET_NULL, null=True)
    created_on = models.DateTimeField(auto_now_add=True)
    url = models.URLField("URL", max_length=256,blank=True)
    description = models.TextField("Description", blank=True)
    votes = models.IntegerField(null=True)
    comments = models.IntegerField(null=True)

    def __unicode__(self):
        return self.title
    
    def count_votes(self):
        self.votes = Vote.objects.filter(post = self).count()

    @property
    def sort_by_votes(self):
        return Vote.objects.filter(post = self).count()

    def count_comments(self):
        self.comments = Comment.objects.filter(post = self).count()

views.py 中的帖子列表

 def NewPostListView(request):

    posts = sorted(Post.objects.all(), key=lambda p: p.sort_by_votes, reverse = True)
    for post in posts:
        post.count_votes()
        print(post)
        post.count_comments()
    context = {
        'posts': posts,
    }
    return render(request,'postlist.html', context)

我正在尝试执行与 posts = Post.objects.all().order_by('count_votes') 等效的操作,但出现“无法解析关键字”错误。到目前为止,使用sorted() 似乎可行,但有时upvote 值不正确。如何获取 QuerySet 以按投票对帖子进行排序?

【问题讨论】:

  • 如果投票字段可以多于一个,请使用 Sum()Post.objects.values("creator").annotate(Count('creator')),sum_votes=Sum('votes')).order_by('sum_votes').
  • 要通过降序简单排序添加最小符号“-”:Post.objects.order_by('-votes')。

标签: django sorting django-models


【解决方案1】:

由于您的函数count_votes 调用了一个名为Votes 的模型,我认为在您的Post 模型中,您有一个Votes 模型的外键,反之亦然。如果没有,我建议这样做。

假设这个,你可以使用annotate

from django.db.models import Count
votes = Post.objects.annotate(count_votes=Count('votes')).order_by('count_votes')

【讨论】:

    【解决方案2】:

    你试过posts = Post.objects.all().order_by('votes')吗?

    count_votesPost的方法,不是属性。但是,votes 是。

    【讨论】:

    • 他想要最大的数字,所以order_by('-votes')更好
    【解决方案3】:

    如果您想将投票设置为 Post 模型的默认排序,您可以在 Post 类 Meta 下设置 ordering 属性

    class Post(models.Model):
        ...
    
        class Meta:
            ordering = "-votes"
    

    请注意负数,因为您要按降序排序(最大值在顶部)

    【讨论】:

      猜你喜欢
      • 2012-10-29
      • 1970-01-01
      • 2010-10-07
      • 2017-02-25
      • 1970-01-01
      • 2014-09-19
      • 2011-07-24
      • 2020-11-18
      • 1970-01-01
      相关资源
      最近更新 更多