如果查询没有结果,则重定向

问题描述 投票:0回答:1

我制作了一个带有输入的页面,该输入连接到该视图:

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')

我已为此查询使用set_name__exact,如果搜索未返回任何对象,我想重定向用户,我该如何处理?我尝试使用if / else语句检查对象,但这似乎不起作用。

django django-views django-queryset
1个回答
0
投票
但是,您可以通过将QuerySet属性设置为allow_empty并覆盖allow_empty = False方法来改变行为,以便在出现dispatch的情况下,您可以重定向:

Http404


0
投票
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')
© www.soinside.com 2019 - 2024. All rights reserved.