gpt4 book ai didi

python - 在 Django ListView 中更新 get_queryset 后如何更改排序?

转载 作者:行者123 更新时间:2023-12-02 19:49:52 26 4
gpt4 key购买 nike

我有一个 ListView ,其中实现了搜索栏功能,但似乎我的排序现在不起作用。我该如何解决?我希望能够在 get_queryset 方法之后按照我想要的方式对列表进行排序..

class MemoListView(LoginRequiredMixin, ListView):
model = Memo
template_name = 'memos/memos.html'
context_object_name = 'memos'

def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['memo_list'] = Memo.objects.all()
return context

def get_ordering(self):
ordering = self.request.GET.get('ordering', '-date_time')
return ordering

def get_queryset(self):
query = self.request.GET.get('q')
if query:
memo_list = Memo.objects.filter(
Q(title__icontains=query) | Q(content__icontains=query))
else:
memo_list = Memo.objects.all()
return memo_list

最佳答案

如果您查看 ListView 的源代码,您会看到这样的类。

class MultipleObjectMixin(ContextMixin):
"""A mixin for views manipulating multiple objects."""
allow_empty = True
queryset = None
model = None
paginate_by = None
paginate_orphans = 0
context_object_name = None
paginator_class = Paginator
page_kwarg = 'page'
ordering = None

def get_queryset(self):
"""
Return the list of items for this view.

The return value must be an iterable and may be an instance of
` QuerySet` in which case `QuerySet` specific behavior will be enabled.
"""
if self.queryset is not None:
queryset = self.queryset
if isinstance(queryset, QuerySet):
queryset = queryset.all()
elif self.model is not None:
queryset = self.model._default_manager.all()
else:
raise ImproperlyConfigured(
"%(cls)s is missing a QuerySet. Define "
"%(cls)s.model, %(cls)s.queryset, or override "
"%(cls)s.get_queryset()." % {
'cls': self.__class__.__name__
}
)
ordering = self.get_ordering()
if ordering:
if isinstance(ordering, str):
ordering = (ordering,)
queryset = queryset.order_by(*ordering)

return queryset

def get_ordering(self):
"""Return the field or fields to use for ordering the queryset."""
return self.ordering

在您的代码中,您将重写 get_ordering() 以提供您想要的排序。但您还重写了调用 get_ordering() 的 get_queryset() 方法。如果您没有重写 get_queryset() 方法,您的排序将被默认的 get_queryset() 方法接受。但由于您要重写 get_queryset() 方法,因此您必须显式使用 get_ordering() 方法。

通过执行类似的操作来更改您的 get_queryset()。

def get_queryset(self):
query = self.request.GET.get('q')
if query:
memo_list = Memo.objects.filter(
Q(title__icontains=query) | Q(content__icontains=query))
else:
memo_list = Memo.objects.all()
ordering = self.get_ordering()
memo_list = memo_list.order_by(ordering)
# The following checks are not needed since your get_ordering() will always only return ONE string
# if ordering and isinstance(ordering, str):
# ordering = (ordering,)
# memo_list = memo_list.order_by(*ordering)
return memo_list

关于python - 在 Django ListView 中更新 get_queryset 后如何更改排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58404779/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com