Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validation on query_params in Django Rest Framework

I want to return model_info only if query_params is given otherwise it should give some error message.

I tried below code but it is giving me keyerror when name is not passed in query params .

from rest_framework.validators import ValidationError

class ModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = ModelName
        fields = ('name', 'abbreviation')

    def validate_name(self, value):
        if value:
            return value
        else:
            raise ValidationError('Enter name')



class ModelNameListList(generics.ListCreateAPIView):
    renderer_classes = (JSONRenderer, )
    serializer_class = ModelSerializer

    def get_queryset(self):
        queryset = ModelName.objects.all()
        name = self.request.query_params['name']
        queryset = queryset.filter(Q(name__icontains=name) | Q(abbreviation__icontains=name)).all()
        return queryset

I cannot use get method because I am also using pagination, If I will use get method it will return me all the results.

When I am using below code in get_queryset I am getting response object has no length

   def get_queryset(self):
        queryset = ModelName.objects.all()
        name = self.request.query_params.get('name', None)
        if name:
            queryset = queryset.filter(Q(name__icontains=name) | Q(abbreviation__icontains=name)).all()
        else:
            content = {'errors': 'name is missing'}
            return Response(content)
        return queryset
like image 919
Harshit Agarwal Avatar asked Sep 19 '15 12:09

Harshit Agarwal


1 Answers

With this function:

  def get_queryset(self):
        queryset = ModelName.objects.all()
        name = self.request.query_params.get('name', None)
        if name:
            queryset = queryset.filter(Q(name__icontains=name) | Q(abbreviation__icontains=name)).all()
        else:
            raise exceptions.ParseError("name not supplied")
        return queryset

You should make sure you are always returning a queryset (or raising an exception if that is how you want to handle it).

like image 66
djq Avatar answered Sep 21 '22 07:09

djq