Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用python(而不是QuerySet)对使用ListView分页的模型应用排序 使用python(而不是QuerySet)对使用ListView分页的模型应用排序_Python_Django_Listview_Django Models_Pagination - Fatal编程技术网

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

使用python(而不是QuerySet)对使用ListView分页的模型应用排序 使用python(而不是QuerySet)对使用ListView分页的模型应用排序,python,django,listview,django-models,pagination,Python,Django,Listview,Django Models,Pagination,我使用带有分页功能的Django ListView来显示模型 由于我需要使用methodfield(需要将param发送给method,因此它必须是一个方法)返回值对模型列表进行排序,所以我无法使用get\u query\u set方法完成排序 由于每个页面都会调用get_context_数据,因此我无法在其中添加排序 class SpotRankingView(ListView): model = Spot template_name = 'places/spot_list.

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

由于我需要使用methodfield(需要将param发送给method,因此它必须是一个方法)返回值对模型列表进行排序,所以我无法使用get\u query\u set方法完成排序

由于每个页面都会调用get_context_数据,因此我无法在其中添加排序

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、按反向日期。由于您使用的是
基于类的视图
,因此可以使用
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')

根据文档,get_ordering将ordering应用于queryset。由于我需要订购,db无法直接完成,我仍然无法解决我的问题