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

Redirect if query has no result

我制作了一个页面,其中包含连接到此视图的输入:

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 语句来检查对象,但这似乎不起作用。

.get_queryset(…) [Django-doc]方法应该return一个QuerySet,而不是列表、元组、HttpResponse

但是,您可以通过将 allow_empty 属性设置为 allow_empty = False 来改变行为,并覆盖 dispatch 方法,这样在 Http404 的情况下,您重定向:

from django.http import Http404
from django.shortcuts import redirect

class SearchResultView(ListView):
    <b>allow_empty = False</b>
    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 <b>dispatch</b>(self, *args, **kwargs):
        try:
            return super().dispatch(*args, **kwargs)
        except <b>Http404</b>:
            return redirect(<i>'core:dashboard'</i>)

就我个人而言,我只是将 .exists 更改为 .count:

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.count():
        return object_list
    else:
        return redirect('core:dashboard')