我正在使用基于类的 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/