django-rest-framework how to make model serializer fields required

后端 未结 5 690
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-05 14:14

I have a model that I\'m filling out step by step, it means I\'m making a form wizard.

Because of that most fields in this model are required but have null=Tru

5条回答
  •  醉梦人生
    2020-12-05 14:43

    You need to override the field specifically and add your own validator. You can read here for more detail http://www.django-rest-framework.org/api-guide/serializers/#specifying-fields-explicitly. This is the example code.

    def required(value):
        if value is None:
            raise serializers.ValidationError('This field is required')
    
    class GameRecord(serializers.ModelSerializer):
        score = IntegerField(validators=[required])
    
        class Meta:
            model = Game
    

提交回复
热议问题