Фильтрация django наборов запросов - PullRequest
0 голосов
/ 07 мая 2020

В проекте у меня есть представление, которое отображается в браузере как панель поиска для поиска рецептов. Я думаю, что есть способ лучше, чем то, как я делаю это прямо сейчас, но понятия не имею, как это сделать. Если я не буду делать то, что делаю прямо сейчас, я получаю сообщение об ошибке, которое нельзя отфильтровать с помощью None.

Я знаю, что могу использовать try exept, но тогда ни одно из значений не может быть 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 голосов
/ 07 мая 2020

Вы можете связать 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)
0 голосов
/ 07 мая 2020
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)
        )

Попробуйте это.

...