I have the following serializer:
class SearchSerializer(serializers.Serializer):
category_id = serializers.IntegerField()
search_term = serializers.CharField(required=False)
I need to validate whether the category with the id exists in the database and retrieve it's value in the view. In order to avoid fetching Category
twice, I have added the following validate()
to the serializer.
def validate(self, data):
try:
category = Category.objects.get(pk=data['category_id'])
except Category.DoesNotExist:
raise serializers.ValidationError('Invalid category_id')
self.data['category'] = category
return data
But it leads to an error.
When a serializer is passed a `data` keyword argument you must call `.is_valid()` before attempting to access the serialized `.data` representation.
You should either call `.is_valid()` first, or access `.initial_data` instead.
Is there a way to do this?
views.py
class SearchView(generics.GenericAPIView):
def get(self, request):
serializer = SearchSerializer(data=request.query_params)
if serializer.is_valid():
category_id = serializer.data['category_id']
category = Category.objects.get(pk=category_id) ## Avoid this check
# TODO: application logic
return Response({'success': True})
return Response(serializer.errors)
Instead of self.data['category'] = category
you need to simply use data['category'] = category
in your validate
method
You should consider using a PrimaryKeyRelatedField
though, like so:
category = serializers.PrimaryKeyRelatedField(
queryset=Category.objects.all(),
error_messages={'does_not_exist': 'Invalid category id'})
and you wouldn't need the validate
at all and you would be able to access the entire Category
object in your view directly as serializer.validated_data['category']
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.