python - 如何在基于类的 View 中进行排序

标签 python django

我正在使用基于类的 View ,例如

class PostListByMostViewedView(ListView):
    model = Post
    template_name = 'community/mostviewed_home.html'  # <app>/<model>_<viewtype>.html
    context_object_name = 'posts'
    ordering = ['-views']
    paginate_by = 5

模型.py

   class Post(models.Model):
        views = models.PositiveIntegerField(default=0)

然后帖子按 View 列出。但 我有不同的型号

class Comment(models.Model):
    post = models.ForeignKey(Post, on_delete=models.CASCADE)

我想按帖子数量订购。 我认为这会起作用

ordering = ['-post.comment_set.count']

但这失败了 没有这样的列:post.comment_set.count

最佳答案

您可以.annotate(..) [Django-doc] Post 对象以及 comment_set 中的项目数,然后 .order_by(..) [Django-doc]该注释:

from django.db.models import <b>Count</b>

class PostListByMostViewedView(ListView):
    model = Post
    queryset = Post.objects.annotate(
        <b>ncomments=Count('comment')</b>
    ).order_by(<b>'-ncomments'</b>)
    template_name = 'community/mostviewed_home.html'
    context_object_name = 'posts'
    paginate_by = 5

令人高兴的是,查询集中的每个 Post 对象现在都有一个额外的属性 ncomments,其中包含评论数量。

关于python - 如何在基于类的 View 中进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56515742/

相关文章:

python - 使用单个 plt.bar() 函数设置条形图标签和值

python - 将所有数据框列转换为 float 的最快方法 - pandas astype slow

python - x 轴上带有日期的不连续时间序列图

python - IndexView 缺少 QuerySet。定义 IndexView.model - tutorial 4 django

python - 在 Python2.7 中使用 'super' 的例子

python - 交互式调整后保存图形参数

django::在测试中调用中间件

html - HTML中的Django Haystack搜索

mysql - geodjango 与 mysql 出现错误 django.db.utils.OperationalError : (1045,“用户访问被拒绝

django - 无法让 django-chosen ChosenSelect 小部件工作