Rest Framework Django - 禁用字段以接受空值

时间:2017-08-23 06:39:31

标签: django django-models django-rest-framework

Rest Framework Django - 禁用字段以接受空值

如何配置序列化模型以接受空白字段?

警告

{"Operacao": ["This field can not be blank."]}

模型

class SEF(models.Model):
    operacao = models.CharField(max_length=10, null=True)
    documento = models.CharField(max_length=50, null=True)
    user = models.ForeignKey(User)

串行

class SEFCreateSerializer(serializers.ModelSerializer):

    class Meta:
        model = SEF
        fields = ('operacao', 'documento', 'user')

查看

sef_create = SEFCreateSerializer(data=data, many=True)
        if sef_create.is_valid():
            sef_create.save()
            salvo = HTTP_200_OK
        else:
            salvo = sef_create.errors

3 个答案:

答案 0 :(得分:1)

class SEFCreateSerializer(ModelSerializer):

    class Meta:
        model = SEF
        fields = ('operacao', 'documento', 'user')
        extra_kwargs = {'operacao': {'required': False}} 

答案 1 :(得分:1)

其工作

operacao = serializers.CharField(allow_blank=True, allow_null=True)

包含allow_blank = True

答案 2 :(得分:0)

您可以设置默认值,如

operacao = models.CharField(max_length=10, default=0)

如果您在模型中指定一个字段,则默认值为0(如果不存在)。

或在序列化程序中

operacao = serializers.CharField(allow_null = True)