首页 > 解决方案 > 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'],
        )

标签: django

解决方案


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(..)功能层面转移了责任。


推荐阅读