如何使用django rest框架序列化器将可空字段设置为None

时间:2017-09-27 14:52:47

标签: django django-rest-framework

我有一个简单的视图,我希望能够将可为空的TimeField设置为无:

class Device(models.Model):
    alarm_push = models.TimeField(null=True, blank=True)

class DeviceSettingsSerializer(serializers.ModelSerializer):
    class Meta:
        model = Device
        fields = ('alarm_push',)


class DeviceSettingsView(RetrieveUpdateAPIView):
    serializer_class = DeviceSettingsSerializer
    lookup_field = 'uuid'

    def get_queryset(self):
        return Device.objects.all()

但如果我尝试修补像{'alarm_push': None}这样的数据,我会收到类似{"alarm_push":["Time has wrong format. Use one of these formats instead: hh:mm[:ss[.uuuuuu]]."]}的错误

如何将alarm_push设置为无?

1 个答案:

答案 0 :(得分:2)

由于您的Serializer是ModelSerializer,DRF将使用TimeField()作为您的alarm_push模型属性。当您签出DRF时间段https://github.com/encode/django-rest-framework/blob/master/rest_framework/fields.py#L1278的源代码时,您可以看到to_internal_value在每次解析值的尝试失败时都会引发错误。

所以要让你的TimeField为空,你应该用空字符串修补{"alarm_push": ""}以表示空状态。