'Django Rest-Framework search-fields wont work inside @action
I'm trying to use the search field offered by DRF inside of an action, but it seems to not work. I had a similar problem paginating inside of the action but found a solution. My guess is that it's overriding the ModelViewSet so I have to manually add the filtering, but is there a way to use the same search_fields offered by DRF. Here's my code:
class XViewSet(ModelViewSet):
queryset = X.objects.all()
serializer_class = XSerializer
permission_classes = [IsAdminUser]
filter_backends = (SearchFilter,OrderingFilter)
search_fields = ['a','b','c','d']
@action(detail=False, methods=['GET'], permission_classes=[IsAuthenticated])
def me(self, request):
query = X.objects.filter(ex_id=request.user.id)
if request.method == 'GET':
serializer = XSerializer(query, many=True)
return Response(serializer.data)
Any help is appreciated, Thank you :)
Solution 1:[1]
I solved it by importing the query param in the beginning, and then filtered the queryset, here's the updated code:
class XViewSet(ModelViewSet):
queryset = X.objects.all()
serializer_class = XSerializer
permission_classes = [IsAdminUser]
filter_backends = (SearchFilter,OrderingFilter)
search_fields = ['a','b','c','d']
@action(detail=False, methods=['GET'], permission_classes=[IsAuthenticated])
def me(self, request):
query = self.get_queryset()
query = query.filter(ex_id=request.user.id)
if request.method == 'GET':
query = self.filter_queryset(query)
serializer = XSerializer(query, many=True)
return Response(serializer.data)
There's probably a better way to write this code but Just wanted to share it with everyone.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | sam rafiei |