我有这些序列化器:
>---id = serializers.IntegerField() >---name = serializers.CharField() >---age = serializers.IntegerField()
现在,我给序列化器这个数据:
{'id': 1, 'name': 'cc'}
我没有给出价值age
.如何age
在序列化器中设置默认值?
我想得到这个,这12
是一个默认值:
{'id': 1, 'name': 'cc', 'age': 12}
小智.. 10
你想在序列化器中设置吗?
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')
Satyajeet.. 9
age = serializers.IntegerField(default=12, initial=12)
初始化为预填充html表单.查看文档
你想在序列化器中设置吗?
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')
age = serializers.IntegerField(default=12, initial=12)
初始化为预填充html表单.查看文档
如您所说,您没有模特
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}
或者,如果您错过了在views.py中指定年龄的信息
serializer = UserSerializer(data={'id': 1, 'name': 'cc'}) serializer.is_valid() # True serializer.validated_data # {'id': 1, 'name': 'cc', 'age': 12}
希望这可以帮助某人:)