djangodjango-viewsdjango-queryset

Redirect if query has no result


I've made a page with an input which connects to this view:

class SearchResultView(ListView):
    model = RecipeSet

    template_name = 'core/set_result.html'
    context_object_name = 'recipe_set'

    def get_queryset(self):
        query = self.request.GET.get('q')
        object_list = RecipeSet.objects.filter(
            Q(set_name__exact=query)
        )
        if object_list.exists():
            return object_list
        else:
            return redirect('core:dashboard')

I've used set_name__exact for this query and want to redirect users if the search returned no objects, how do I go about this? I've tried to use an if/else statement to check the objects but that doesn't seem to work.


Solution

  • The .get_queryset(…) [Django-doc] method should return a QuerySet, not a list, tuple, HttpResponse, etc.

    You can however alter the behavior, by setting the allow_empty attribute to allow_empty = False, and override the dispatch method such that in case of a Http404, you redirect:

    from django.http import Http404
    from django.shortcuts import redirect
    
    class SearchResultView(ListView):
        allow_empty = False
        model = RecipeSet
        template_name = 'core/set_result.html'
        context_object_name = 'recipe_set'
        
        def get_queryset(self):
            return RecipeSet.objects.filter(
                set_name=self.request.GET.get('q')
            )
    
        def dispatch(self, *args, **kwargs):
            try:
                return super().dispatch(*args, **kwargs)
            except Http404:
                return redirect('core:dashboard')