切片后重新排序Django查询

时间:2015-08-03 19:30:34

标签: python django django-models django-views django-queryset

有没有办法在切片拍摄后重新排序Django查询?

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

models.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]

views.py:

def home(request):
    most_commented = Photo.objects.most_commented()
    photos = most_commented.order_by('?')

    context = {
        'photos': photos
    }
return render(request, 'home.html', context)

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

提前谢谢!

1 个答案:

答案 0 :(得分:5)

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

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)