是否有办法在切片后重新排序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张图片,然后随机排列它们的显示顺序。
提前感谢!
将照片转换为列表,然后正常洗牌:
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)