jeudi 7 mai 2020

Filtering django querysets

In a project I have a view wich displays in the browser as a searchbar to search recipes. I think there is a better way then how I'm doing it right now, but have no idea how. If I don't do what I'm doing right now, I get the error that you can't filter with None.

I know I could use a try exept but then none of the values may be None or an error is raised.

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



Aucun commentaire:

Enregistrer un commentaire