【问题标题】:Redirect if query has no result如果查询没有结果则重定向
【发布时间】:2020-05-29 20:39:13
【问题描述】:

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

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】:

    .get_queryset(…) [Django-doc] 方法应返回 QuerySet,而不是列表、元组、HttpResponse 等。

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

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

    【讨论】:

    • 这正是我想要的!我不确定我在查看文档时怎么没有遇到 allow_empy ......感谢您提供的信息!
    【解决方案2】:

    我个人只是将 .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')
    

    【讨论】:

    • 但是通过返回HttpRedirectResponse(通过redirect 调用),这将出错,因为get_queryset 不应该返回其他内容。
    • 我个人更喜欢.count() > 0
    • @Uri: 好吧.exists() 有时比.count() 快,因为如果没有索引,存在可以从找到一条记录的那一刻起停止,而.count() 在这种情况下应该继续搜索更多记录以计算项目总数。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-11-27
    • 2015-02-13
    • 2015-09-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-30
    相关资源
    最近更新 更多