我目前正在尝试添加过滤器到菜单API,但它似乎不工作
这是我在www.example.com中尝试的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)
每当我转到设置了过滤器值的端点时,我都会得到一个空列表,而不是过滤后的菜单项列表:
empty list when filtered
这是没有过滤的情况:
menu items list unfiltered
我做错什么了吗?我正在遵循一个教程,它对教程有效,但对我的无效。
1条答案
按热度按时间zsbz8rwp1#
在我看来,你的标题是以大写字母开头的。
您可以通过执行以下操作实现不区分大小写的搜索: