Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storing Default Values for BooleanField() and IntegerField() in Django REST

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 ?

like image 724
felix001 Avatar asked Jul 14 '15 06:07

felix001


1 Answers

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.
  • If you want to allow null inputs for boolean fields you need to use the 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.

like image 176
Tom Christie Avatar answered Oct 11 '22 03:10

Tom Christie