I know as per the documentation the following fields do not take allow_blank=True
and allow_null=True
BooleanField()
IntegerField()
I need to allow the client to not specify g or d (as per below) and to store the value in the DB as None
.
g = serializers.BooleanField()
d = serializers.IntegerField()
Any ideas ?
The different options for handling of empty, blank and null fields are (necessarily) a little subtle, so its unsurprising that it sometimes trips folks up.
I know as per the documentation the following fields do not take allow_blank=True and allow_null=True
That's incorrect:
IntegerField(allow_null=True)
is valid.NullBooleanField()
class.You are correct that neither of them take allow_blank
, as the empty string isn't going to be a valid value in either case.
I need to allow the client to not specify g or d (as per below) and to store the value in the DB as None.
You can either use IntegerField(default=None)
and NullBooleanField(default=None)
.
In this case when the values are omitted they will be included as None
in serializer.validated_data
. You'll want to make sure you use null=True
/NullBooleanField
on the model field.
Or IntegerField(required=False)
and NullBooleanField(required=False)
.
In this case when the values are omitted they will not be included in serializer.validated_data
, and the model field default will be used. You'll want to make sure you use default=None
and null=True
/NullBooleanField
on the model field.
Note that there was a bug when using the Browsable API that empty fields in HTML input did not get the default values set. This is resolved in the upcoming 3.1.4 release.
The initial
argument suggested in Edwin's answer can also be useful, but is for setting an value to be initially rendered in HTML form fields.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With