David Schumann
David Schumann

Reputation: 14793

How to set nullable field to None using django rest frameworks serializers

I have a simple view with which I want to be able to set a nullable TimeField to None:

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()

But if I try to PATCH data like {'alarm_push': None} I get an error like {"alarm_push":["Time has wrong format. Use one of these formats instead: hh:mm[:ss[.uuuuuu]]."]}

How can I set alarm_push to None?

Upvotes: 0

Views: 1102

Answers (1)

Johannes Reichard
Johannes Reichard

Reputation: 947

As your Serializer is a ModelSerializer DRF will use a TimeField() for your alarm_push model attribute. When you checkout the sourcecode of the DRF Timefield https://github.com/encode/django-rest-framework/blob/master/rest_framework/fields.py#L1278 you can see that to_internal_value is raising your error when every attempt of parsing the value failes.

So to have your TimeField be empty you should patch {"alarm_push": ""} with an empty string to represent an empty state.

Upvotes: 2

Related Questions