在sli之后重新排序Django查询

2024-10-02 06:25:57 发布

您现在位置:Python中文网/ 问答频道 /正文

有没有一种方法可以在获取切片后重新排序Django查询?在

我正在尝试执行以下操作,但出现以下错误:Cannot reorder a query once a slice has been taken.

模型.py:

class PhotoManager(models.Manager):
    def most_commented(self):
        return super(PhotoManager, self).get_queryset().annotate(
            the_count=(Count('comment'))).order_by('-the_count')[:100]

视图.py:

^{pr2}$

我的目标是获取前100个评论最多的图片,然后随机排列它们的显示顺序。在

提前谢谢你!在


Tags: thedjango方法pyself排序count错误
1条回答
网友
1楼 · 发布于 2024-10-02 06:25:57

将照片转换为列表,然后正常洗牌:

import random

...

def home(request):
    most_commented = Photo.objects.most_commented()
    photos = list(most_commented)
    random.shuffle(photos)
    context = {
        'photos': photos
    }
    return render(request, 'home.html', context)

相关问题 更多 >

    热门问题