切片后重新排序 Django 查询
Reorder a Django query after slice
有没有办法在获取切片后重新排序 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)
有没有办法在获取切片后重新排序 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)