【问题标题】:Filtering django querysets过滤 Django 查询集
【发布时间】:2020-08-22 10:00:39
【问题描述】:

在一个项目中,我有一个视图,它显示在浏览器中作为搜索栏来搜索食谱。我认为有比我现在做的更好的方法,但不知道如何做。如果我现在不做我正在做的事情,我会收到您无法使用 None 过滤的错误。

我知道我可以使用 try except 但没有任何值可能是 None 或引发错误。

class SearchResultListViewOther(ListView):
    model = Recipe
    template_name = 'recipes/search_other.html'
    extra_context = {
        'time': time,
        'categorie': categorie,
        'continent': continent,
    }

    def get_queryset(self):
        """
        Filter out recipes by some other params like the title
        """
        # Can not filter on None so set a value if no search params were given
        title = self.request.GET.get('title')
        if not title:
            title = '0'
        time_recipe = self.request.GET.get('time')
        if not time_recipe:
            time_recipe = 0
        continent_recipe = self.request.GET.get('continent')
        if not continent_recipe:
            continent_recipe = '0'
        object_list = Recipe.objects.filter(
            Q(title__icontains=title) | Q(time__lte=time_recipe) |
            Q(continent__exact=continent_recipe)
            )
        return object_list

【问题讨论】:

    标签: python django web search django-views


    【解决方案1】:

    您可以使用&=|= 操作链接Q 查询。

    def get_queryset(self):
        """
        Filter out recipes by some other params like the title
        """
        title = self.request.GET.get('title')
        time_recipe = self.request.GET.get('time')
        continent_recipe = self.request.GET.get('continent')
    
        # default empty query
        q = Q()
        if title:
            q |= Q(title__icontains=title)
        if time_recipe:
            q |= Q(time__lte=time_recipe)
        if continent_recipe:
            q |= Q(continent__exact=continent_recipe)
        return  Recipe.objects.filter(q)
    

    【讨论】:

    • 不客气!如果它解决了您的问题,请不要忘记接受答案;)
    • 伟大的解决方案人,现在我的代码看起来不那么愚蠢了,谢谢!
    【解决方案2】:
    def get_queryset(self):
        """
        Filter out recipes by some other params like the title
        """
        # Can not filter on None so set a value if no search params were given
        title = self.request.GET.get('title')
        time_recipe = self.request.GET.get('time')
        continent_recipe = self.request.GET.get('continent')
        if title or time_recipe or continent_recipe:
            return  Recipe.objects.filter(
            Q(title__icontains=title) | Q(time__lte=time_recipe) |
            Q(continent__exact=continent_recipe)
            )
    

    请试试这个。

    【讨论】:

    • 你不需要使用 if _ and _ and _: 因为它们都不可能是 None 吗?
    • 如果我们使用 and,如果 title 是 None 但 time_recipe 不是,它将失败。
    • 这不能解决我的问题。因为这里仍然有可能 title、time_recipe 或continent_recipe 进入值为 None 的 if。在这种情况下,只需一个人在场
    猜你喜欢
    • 2019-04-15
    • 2011-09-29
    • 2019-03-16
    • 2018-10-02
    • 2019-07-29
    • 2023-04-03
    相关资源
    最近更新 更多