[Django]-How can I set default value in serializers?

9πŸ‘

βœ…

If you make a model field blank, you can set a default value that will be filled in if you don’t supply a value on the POST:

class Foo(models.Model):
    bar = models.IntegerField(blank=True, default=42)
                             #^^^^^^^^^^  ^^^^^^^^^^

Then, when you POST use {} as the data

πŸ‘€Ross Rogers

21πŸ‘

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

initial to pre populate html form.
See the docs

πŸ‘€Satyajeet

17πŸ‘

do you want to set in serializers?

class PersonSerializer(serializers.ModelSerializer):
   age = serializers.SerializerMethodField()

   def get_age(self, obj):
       return getattr(obj, 'age', 12)

   class Meta:
       model = Person
       field = ('id', 'name', 'age')
πŸ‘€third9

15πŸ‘

As you said, you don’t have a model

1.serializer.py

class UserSerializer(serializers.Serializer):
    id = serializers.IntegerField()
    name = serializers.CharField()
    age = serializers.IntegerField(default=12) #if key age is missing, value of age become 12

    def validate(self,data):
        #other wise you can set default value of age here,
        if data.get('age',None)==None: #this conditon will be true only when age = serializer.IntergerField(required=False)
            data['age']=12
        return data

views.py

serializer = UserSerializer(data={'id': 1, 'name': 'cc', 'age': 14})
serializer.is_valid()
# True
serializer.validated_data
# {'id': 1, 'name': 'cc', 'age': 14} 

or if you miss specifying age in views.py

serializer = UserSerializer(data={'id': 1, 'name': 'cc'})
serializer.is_valid()
# True
serializer.validated_data
# {'id': 1, 'name': 'cc', 'age': 12} 

Hope this help someone πŸ™‚

πŸ‘€vijay

Leave a comment