小编典典

django-rest-framework如何使模型序列化器字段必填

django

我有一个逐步填写的模型,这意味着我正在制作一个表单向导。

因此,此模型中的大多数字段都是必需的,但必须null=True, blank=True避免在提交部分数据时引发非空错误。

我正在使用Angular.js和django-rest-framework,我需要告诉api应该是x和y字段,如果它们为空,则需要返回验证错误。


阅读 849

收藏
2020-04-03

共2个答案

小编典典

你需要专门覆盖该字段并添加自己的验证器。你可以在此处详细了解http://www.django-rest-framework.org/api-guide/serializers/#specifying-fields-explicitly。这是示例代码。

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
2020-04-03
小编典典

根据文档,最好的选择是在类Meta中使用extra_kwargs,例如,你具有存储电话号码的UserProfile模型,并且该模型是必需的

class UserProfileSerializer(serializers.ModelSerializer):
    class Meta:
        model = UserProfile
        fields = ('phone_number',)
        extra_kwargs = {'phone_number': {'required': True}} 
2020-04-03