Skip to content
thesarfo

Note

Deserializing Data

Turning incoming POST data back into a model instance, validating it, and returning a 400 with error details when it's invalid.

views 0

Deserializing simply involves converting the object from a dictionary into the actual object to be stored in the database. For instance, a user wants to create a new product, they make a post request to the product endpoint and the product details come in a dictionary/json format. Now we need to convert this dictionary into something we can store in our database. That is the concept of serialization.

First in our view function we need to specify the http methods that are allowed on it. Since a user will be creating a resource we need to allow POST method on our view function.

Now, based on the http method, we do something. see below

@api_view(['GET', 'POST'])
def product_list(request):
if request.method == 'GET':
'''get all the products'''
queryset = Product.objects.select_related('collection').all()
serializer = ProductSerializer(queryset, many=True, context={'request': request})
return Response(serializer.data)
elif request.method == 'POST':
'''read the data in the body of the data and deserialize it'''
serializer = ProductSerializer(data=request.data) #ProductSerializer is going to desirialize what is in the bracket
return Response('ok')

The deserialized object is stored in “serializer.validated_data”, which is a dictionary. But before you can access the deserialized object or even access its validated_data, you have to perform a data validation or you will get an error.

So now we need to check if the data is valid, if it is we access the validated_data else we return an error response to the client. see below

@api_view(['GET', 'POST'])
def product_list(request):
if request.method == 'GET':
queryset = Product.objects.select_related('collection').all()
serializer = ProductSerializer(queryset, many=True, context={'request': request})
return Response(serializer.data)
elif request.method == 'POST':
serializer = ProductSerializer(data=request.data)
if serialiazer.is_valid():
serializer.validated_data
return Response('ok')
else:
'''http 400 has been imported at the top of the views file'''
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

There is another way to perform this deserialization and return error, but this method is way neater than the one above

@api_view(['GET', 'POST'])
def product_list(request):
if request.method == 'GET':
queryset = Product.objects.select_related('collection').all()
serializer = ProductSerializer(queryset, many=True, context={'request': request})
return Response(serializer.data)
elif request.method == 'POST':
serializer = ProductSerializer(data=request.data)
'''we do the validation and error handling below'''
serializer.is_valid(raise_exception=True)
serializer.validated_data
return Response('ok')