Reputation: 901
I have to implement set of filters (see picture). My code works fine for 1 filter e.g.
http://127.0.0.1:8000/api/constructions?field=developer&value=1 -- filter by developer with id =1
I want to filter by several filters in one request. I can use something like this
Is there better way to solve my issue?
views.py
class ConstructionView(viewsets.ModelViewSet):
serializer_class = ConstructionSerializer
queryset = Construction.objects.all()
pagination_class = BasePagination
def list(self, request):
field = request.GET.get('field', None)
value = request.GET.get('value', None)
if field is not None and value is not None:
queryset = Construction.objects.filter(**{field:value})
else:
queryset = Construction.objects.all()
page = self.paginate_queryset(queryset)
if page is not None:
serializer = ConstructionSerializer(page, many=True)
return self.get_paginated_response(serializer.data)
else:
serializer = ConstructionSerializer(queryset, many=True)
return Response(serializer.data, status=status.HTTP_200_OK)
Upvotes: 0
Views: 66
Reputation: 119
If you want to get multiple object by their ID, you can try something like this:
Construction.objects.filter(id__in = [1,2])
It will return objects with 1,2 IDs
Upvotes: 1
Reputation: 646
If you have a list at your query_params
you can use that approach. You can check if your value of your query_params
is a list or string and apply it to a filter. <fieldname>__in
works for list.
custom_filter = {'field__in': request.query_params.get('field'), 'value__in': request.query_params.get('value')}
queryset = Construction.objects.filter(**custom_filter )
Maybe djangorestframework-queryfields helps your for a bunch of common work.
Upvotes: 1