Django highly suggests not to use
The convention implied from the Django code seems to be to store null JSON values as NULL as opposed to as an empty string (as is the convention for the
CharField). I say this because of the following:
empty_strings_allowed is inherited from
CharField, and is set to
class Field(RegisterLookupMixin): """Base class for all field types""" # Designates whether empty strings fundamentally are allowed at the # database level. empty_strings_allowed = True ...
JSONField, however, overrides it with
class JSONField(Field): empty_strings_allowed = False ...
CharField's to default to
None when you instantiate a model without explicitly passing the values for these fields.
def get_default(self): """ Returns the default value for this field. """ if self.has_default(): if callable(self.default): return self.default() return self.default if (not self.empty_strings_allowed or (self.null and not connection.features.interprets_empty_strings_as_nulls)): return None return ""
Therefore, if you want to make a
JSONField optional, you have to use:
json_field = JSONField(blank=True, null=True)
If you use only
blank=True, as you would for
CharField, you'll get an
IntegrityError when trying to run
MyModel.objects.create(...) without passing a
json_field argument explicitly.