Django:ListView 的 get_object_or_404

标签 django

我有以下 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/

相关文章:

django - Django 项目/配置目录是否有命名约定?

django - pytest,如何在测试之间保持数据库更改

django - 用户因数据迁移而登录失败

django - 无法为 Django 应用程序使用相对名称

django 表单 : default values for bound forms

python - 使用第二个模型的外键时未定义模型

python - Django Compressor 空白 Css 输出文件

python - django-tastypie 能否在单个资源的列表和详细 View 中显示一组不同的字段?

django - 如何为Django模型Integerfield分配默认值,而相关的FormField是可选的?

python - 让 Django SplitDateTimeField 接受空时间字段的更好方法?