我正在使用基于类的视图,例如
class PostListByMostViewedView(ListView):
model = Post
template_name = 'community/mostviewed_home.html' # <app>/<model>_<viewtype>.html
context_object_name = 'posts'
ordering = ['-views']
paginate_by = 5
Models.py
class Post(models.Model):
views = models.PositiveIntegerField(default=0)
然后按视图列出帖子。但 我有不同的型号
class Comment(models.Model):
post = models.ForeignKey(Post, on_delete=models.CASCADE)
我想按帖子数订购。 我以为这可以工作
ordering = ['-post.comment_set.count']
但这失败了 没有这样的列:post.comment_set.count
答案 0 :(得分:2)
您可以.annotate(..)
[Django-doc]个<?php
$z = file('q1.txt'); echo $z[1]; echo (mt_rand(1,9));
$st = array($z[1]);
foreach($st as $ls) {echo " <li>$ls</li>\n";}
对象和Post
中的项目数,然后.order_by(..)
[Django-doc]该注释:
comment_set
令人高兴的是,查询集中的每个from django.db.models import Count
class PostListByMostViewedView(ListView):
model = Post
queryset = Post.objects.annotate(
ncomments=Count('comment')
).order_by('-ncomments')
template_name = 'community/mostviewed_home.html'
context_object_name = 'posts'
paginate_by = 5
对象现在都有一个额外的属性Post
,其中包含注释的数量。