Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get serializer field value in api-view

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.

like image 861
Sebastian Olsen Avatar asked Apr 21 '16 13:04

Sebastian Olsen


People also ask

What does serializer Is_valid () do?

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.

What does serializer data return?

The BaseSerializer class caches its data attribute on the object, but Serializer. data returns a copy of BaseSerializer.

What is Serializers SerializerMethodField ()?

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)

What is the difference between ModelSerializer and serializer?

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.


2 Answers

I figured it out myself, you need to reference the "data" class inside the serializer:

serializer.data['title']
like image 162
Sebastian Olsen Avatar answered Sep 28 '22 07:09

Sebastian Olsen


Before .save method you should use validated_data to access fields

serialiser.validated_data['title'] 
like image 41
Vishal Sharma Avatar answered Sep 28 '22 07:09

Vishal Sharma