过滤Django查询集

时间:2020-05-07 07:31:35

标签: python django web search django-views

在一个项目中,我有一个视图,该视图在浏览器中显示为搜索配方的搜索栏。我认为现在有一种更好的方法,但不知道如何做。如果我不做我现在正在做的事情,则会收到您无法使用“无”进行过滤的错误。

我知道我可以尝试一下,但是所有的值都不能为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

2 个答案:

答案 0 :(得分:0)

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

请尝试这个。

答案 1 :(得分:0)

您可以使用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)