17

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

1 Answer 1

6

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).

Sign up to request clarification or add additional context in comments.

2 Comments

Should probably be exceptions.ValidationError -- ParseError is reserved for malformed data according to the docs whereas ValidationError is for well-formed data that doesn't meet the validation guidelines.
@connorbode i was thinking same but when i try to raise ValidationError from View it throws server 500 error says Validation Error at ./../ instead of a well formed JSON response. I think ValidationError is stick to Serializers. not sure

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.