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 :
- any better approach for the validation
- what is the different between validation at view and serializers level
- 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.