Filtering With DRF

37 views Asked by At

I'm currently trying to add filter to a menu API but it doesn't seem to work

This is what I tried in my views.py:

@api_view()
def menu_items(request):
    if request.method == "GET":
        items = MenuItem.objects.select_related('category').all()
        category_name = request.query_params.get('category')
        to_price = request.query_params.get('to_price')
        search = request.query_params.get('search')
        if category_name:
            items = items.filter(category__title=category_name)
        if to_price is not None:
            items = items.filter(price__lte=to_price) # lte means price is less then or equal to the value to_price
        if search:.
            items = items.filter(title__icontains=search) # If the characters are present anywhere in the title. This is case insensitive.
        serialized_item = MenuItemSerializer(items, many=True)
        return Response(serialized_item.data)
    if request.method == 'POST':
        serialized_item = MenuItemSerializer(data=request.data)
        serialized_item.is_valid(raise_exception=True)
        serialized_item.save() # Saves the validated data to the database
        return Response(serialized_item.data, status.HTTP_201_CREATED)

Whenever I go to the endpoint with the filter value set up, I get an empty list instead of a list of filtered menu items:

empty list when filtered

This is what it looks like without filtering:

menu items list unfiltered

Am I doing something wrong? I am following a tutorial and it works on the tutorial but not on mine.

1

There are 1 answers

0
Alombaros On

It seems to me that your titles start with an uppercase letter.
You can achieve case insensitive search by doing:

if category_name:
    items = items.filter(category__title__iexact=category_name