gpt4 book ai didi

Django:ListView 的 get_object_or_404

转载 作者:行者123 更新时间:2023-12-01 12:35:42 24 4
gpt4 key购买 nike

我有以下 ListView。我知道 get_object_or_404。但是,如果对象 不存在,是否有办法显示 404 页面?

class OrderListView(ListView):

template_name = 'orders/order_list.html'

def get_queryset(self):
return OrderItem.objects.filter(
order__order_reference=self.kwargs['order_reference'],
)

最佳答案

您可以通过更改 allow_empty [django-doc]ListView 引发 404 错误属性为 False:

class OrderListView(ListView):

template_name = 'orders/order_list.html'
<b>allow_empty = False</b>

def get_queryset(self):
return OrderItem.objects.filter(
order__order_reference=self.kwargs['order_reference'],
)

如果我们检查 BaseListView 的源代码(该类是 ListView 类的祖先之一),那么我们会看到:

class BaseListView(MultipleObjectMixin, View):
"""A base view for displaying a list of objects."""
def get(self, request, *args, **kwargs):
self.object_list = self.get_queryset()
<b>allow_empty = self.get_allow_empty()</b>

if <b>not allow_empty</b>:
# When pagination is enabled and object_list is a queryset,
# it's better to do a cheap query than to load the unpaginated
# queryset in memory.
if self.get_paginate_by(self.object_list) is not None and hasattr(self.object_list, 'exists'):
is_empty = not self.object_list.exists()
else:
is_empty = not self.object_list
<b>if is_empty:
raise Http404(_("Empty list and '%(class_name)s.allow_empty' is False.") % {
'class_name': self.__class__.__name__,
})</b>
context = self.get_context_data()
return self.render_to_response(context)

所以它也考虑到了分页等,将责任转移到了get(..)函数层面。

关于Django:ListView 的 get_object_or_404,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51058343/

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