Django:用于ListView的get_object_or_404

时间:2018-06-27 08:44:59

标签: django

我有以下ListView。我知道get_object_or_404。但是如果 object 不存在,有没有办法显示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'],
        )

2 个答案:

答案 0 :(得分:3)

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

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(..)功能级别上转移了责任。

答案 1 :(得分:2)

您可以使用get_list_or_404

from django.shortcuts import get_list_or_404

def get_queryset(self):
    my_objects = get_list_or_404(OrderItem, order__order_reference=self.kwargs['order_reference'])