Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I set default value in serializers?

I have these serializers:

>---id = serializers.IntegerField()
>---name = serializers.CharField()
>---age = serializers.IntegerField()  

Now, I give the serializers this data:

{'id': 1, 'name': 'cc'}

I don't give a value for age. how can I set a default value to age in the serializers?

I want to get this, where the 12 is a default value:

{'id': 1, 'name': 'cc', 'age': 12}
like image 638
nataila Avatar asked Dec 11 '15 03:12

nataila


People also ask

Is it necessary to use Serializers in Django?

Serializers in Django REST Framework are responsible for converting objects into data types understandable by javascript and front-end frameworks. Serializers also provide deserialization, allowing parsed data to be converted back into complex types, after first validating the incoming data.

What is 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. It includes simple default implementations of .

What is the use of Serializers?

Serializers allow complex data such as querysets and model instances to be converted to native Python datatypes that can then be easily rendered into JSON , XML or other content types.

What does serializer Is_valid do?

it validates your serializer with the condition of respective field specified in your serializer MessageSerializer .


1 Answers

age = serializers.IntegerField(default=12, initial=12)

initial to pre populate html form. See the docs

like image 110
Satyajeet Avatar answered Oct 12 '22 22:10

Satyajeet