简体   繁体   中英

DRF: Filter several fields in one request

I have to implement set of filters (see picture). My code works fine for 1 filter eg

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

  1. http://127.0.0.1:8000/api/constructions?field=field1_field2&value=value1_value2
  2. Split field1_field2 --> [field1, field2] and so on (it's not perfect)

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)

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM