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
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With