使用 python(不是 QuerySet)将排序应用于使用 ListView 分页的模型


使用

python(不是 QuerySet(将排序应用于使用 ListView 分页的模型

我使用具有分页功能的Django ListView来显示模型。

由于我需要使用方法字段对模型列表进行排序(需要将参数发送到方法,因此它必须是方法(返回值,因此我无法使用get_query_set方法完成排序。

由于每个页面都调用了get_context_data,因此我无法在其中添加排序。

class SpotRankingView(ListView):
model = Spot
template_name = 'places/spot_list.html'
paginate_by = 5

def get_context_data(self, **kwargs):
context = super(SpotRankingView, self).get_context_data(**kwargs)
# This is called for every page
# So I cannot add sort here
return context

def get_queryset(self):
# I need method return value to sort models
#
# ex. I need something like blow to sort models
# method category as blow is a calculated property on model.
# spot.category(category_name = 'Relaxing').points
#
# Those cannot be done by QuerySet so I caanot add that
# sorting here
return Spot.objects.all()

如何使用python列表排序对模型进行排序并使它们分页?

不确定您需要哪种排序。有很多排序方法,例如按日期、按 id、按反向日期。由于您正在使用Class Based Views因此您可以使用如下所示ArchiveIndexView

from django.views.generic.dates import ArchiveIndexView
class SpotRankingView(ArchiveIndexView):
model = Spot
template_name = 'places/spot_list.html'
paginate_by = 5
date_field = "date_created"

如果要在将来显示带有日期的对象,则需要将allow_future设置为True。如果您仍然不明白,请按照参考进行操作。

您还可以为列表视图执行此操作,例如:

class SpotRankingView(ListView):
model = Spot
template_name = 'places/spot_list.html'
paginate_by = 5
def get_ordering(self):
ordering = self.request.GET.get('ordering', '-date_created')

最新更新