13👍
✅
You are accessing the data in a wrong way. You should access .validated_data
on the serializer instead of .data
.
m = CartSerializer(data=inputdata)
if m.is_valid():
items = m.validated_data # access validated data here
Why serializer.data
approach did not work for your case?
When you are doing .data
, the serializer will try to serialize the initial_data
as you have not passed the instance
argument. It will expect all the fields to be present but since cart_color
is not present on the data, it will raise a KeyError
.
When should you generally use serializer.data
then?
You should generally use serializer.data
when you are serializing an existing object. This would require you to pass an instance
argument when creating an instance of the serializer.
m = CartSerializer(instance=my_object)
items = m.data # use .data when serializing an object
Source:stackexchange.com