Im currently trying to allow users to search my database from the client side and return the response to them. I'm a little confused on where in the view I need to support the search query, or if the way I'm going about it is even correct. I've done some research already and found out about the SearchFilter from DRF but unsure how to incorporate it into my code.
Here is my views for the resource i'm trying to search:
class Recipes(ViewSet):
def list(self, request):
recipes = Recipe.objects.all()
user = self.request.query_params.get('user', None)
if user is not None:
recipes = recipes.filter(author = user)
serializer = RecipeSerializer(recipes, many=True, context={'request': request})
return Response(serializer.data)
def retrieve(self, request, pk=None):
try:
recipe = Recipe.objects.get(pk=pk)
serializer = RecipeSerializer(recipe, context={'request': request})
return Response(serializer.data)
except Exception as ex:
return HttpResponseServerError(ex)
Based on my research I've found that I can use:
serializer_class = RecipeSerializer
queryset = Recipe.objects.all()
filter_backends = (SearchFilter,)
filter_fields = ('title', 'ingredients')
in some way but i'm not exactly sure how. Any guidance is appreciated
question from:
https://stackoverflow.com/questions/65601089/supporting-search-queries-in-django-rest-framework 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…