Is it possible to get a field value from a serialized object in Django Rest Framework? Something like this:
serializer = PostSerializer(post)
print(serializer.title)
# 'foo title'
I need this for fields that are added in the serializer, but are not already on the model, like if the logged in user has liked the post.
The .is_valid() method takes an optional raise_exception flag that will cause it to raise a serializers.ValidationError exception if there are validation errors.
The BaseSerializer class caches its data attribute on the object, but Serializer. data returns a copy of BaseSerializer.
SerializerMethodField. This is a read-only field. It gets its value by calling a method on the serializer class it is attached to. It can be used to add any sort of data to the serialized representation of your object. Signature: SerializerMethodField(method_name=None)
The ModelSerializer class is the same as a regular Serializer class, except that: It will automatically generate a set of fields for you, based on the model. It will automatically generate validators for the serializer, such as unique_together validators.
I figured it out myself, you need to reference the "data" class inside the serializer:
serializer.data['title']
Before .save method you should use validated_data to access fields
serialiser.validated_data['title']
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