Search code examples
djangodjango-generic-views

Django: Handling empty querysets in generic view


I am having a generic view which sometimes returns nothing.

How can I effectively handle it and raise a 404 in that case?

My approach is successfull, but hits the database.

class MyListView(ListView):
    template_name = 'template/quest.html'

    def get_queryset(self, *args, **kwargs):

        query = (
            MyModel.objects
            .filter(...)
            .filter(...)
        )

        if query.exists():
            return query
        else:
            raise Http404

Solution

  • Set allow_empty to False:

    class MyListView(ListView):
        allow_empty = False
        template_name = 'template/quest.html'
    
        def get_queryset(self, *args, **kwargs):
            return MyModel.objects.filter(...)
    

    This will raise a Http404 if the result of get_queryset() is empty (has length 0).