django - Django:ListView 的 get_object_or_404
问题描述
我有以下列表视图。我知道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'],
)
解决方案
ListView
您可以通过将allow_empty
[django-doc]属性更改为 来引发 404 错误False
:
class OrderListView(ListView):
template_name = 'orders/order_list.html'
allow_empty = False
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() allow_empty = self.get_allow_empty() if not allow_empty: # 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 if is_empty: raise Http404(_("Empty list and '%(class_name)s.allow_empty' is False.") % { 'class_name': self.__class__.__name__, }) context = self.get_context_data() return self.render_to_response(context)
所以它也考虑到了分页等,并在get(..)
功能层面转移了责任。
推荐阅读
- javascript - 无法单击 selenium webdriver 中的剑道下拉菜单
- excel - 当“On Error Resume Next”将先前的值留在变量中时,如何返回空白或零?
- php - 我可以在模型中添加新键吗?
- django - 在没有循环的情况下从模板中的数据库中获取内容?
- hyperledger-fabric - 使用 go sdk 开发一个超级账本结构链码好吗?
- laravel - 如果项目(多个项目)将在几天后过期,如何通知管理员-Laravel
- node.js - 在 mongoosejs 中执行创建后使用结果填充数据
- reactjs - React:基于对象状态数组的过滤表?
- javascript - 当我更改窗口大小时,我的图像没有像我期望的那样在图像轮播中缩放
- python - 动态嵌套循环 - 递归