How to simplify DRF GET query params validation and request set filter

Viewed 534

I am very new to DRF and have requirement the REST API URL using DRF that will allow 2 or multiple parameters but one parameter should be required i.e: period is required and entity can be blank

http://127.0.0.1:8000/myapi/?entity=&period=FEB-21

I have created the APIView as below:

class myAPI_Viw(APIView):
    serializer_class = myAPI_Serializers
    
    def get(self, request, format=None):
        entity_param = self.request.query_params.get('entity')
        period_param = self.request.query_params.get('period')

        if (entity_param in (None, '') and period_param in (None, '')):
            return Response({"status": "Error", "data": "Invalid parameter, period should have value"}, status=status.HTTP_400_BAD_REQUEST)

        if (entity_param in (None, '') and period_param not in (None, '')):
            rs = myAPI.objects.filter(period_name=period_param)
            print(rs.query)
        else:
            rs = myAPI.objects.filter(entity=entity_param, period_name=period_param)
            print(rs.query)
        serializer = myAPI_Serializers(rs, many=True)
        return Response({"status": "Success", "data": serializer.data}, status=status.HTTP_200_OK)

The above code run correctly. Just wondering if :

  1. any better approach for the validation
  2. what is the different between validation at view and serializers level
  3. is there any way to combine the filter into one call so that entity=entity_param will work eventhough the value passed in is blank

Many thanks in advance, efends

2.

1 Answers

Your Questions Answers:

  1. You can use decorator for validation purpose.
  2. serializer's validation method is called only for POST, PATCH AND PUT requests. So, for GET request if you need validation then you have to validate it on the view (for clean code, you can use decorator)
  3. You can directly filter with entity_param even though it's None. In this case you will get empty queryset.
Related