Hey all,
I’m not sure if this is the right place for this or not, but essentially the issue is this:
forms.JSONField’s to_python method causes the returned value to be None if the provided value is an empty tuple, list or dict.
This also means that the behavior is inconsistent between whether an object/list/tuple is passed to to_python, or a JSON encoded string:
field.to_python([]) # None
field.to_python('[]') # []
This is due to empty_values inheriting the default value from forms.Field.
Aside from being odd, it causes an issue for, as an example, forms.ModelForm, as this can lead to a non-nullable model field being set to None incorrectly. Eg:
class Example(models.Model):
example = models.JSONField(default=list)
class ExampleForm(forms.ModelForm):
example = forms.JSONField(required=False)
class Meta:
model = Example
fields = [
'example'
]
form = ExampleForm({"example": []})
form.save() # attempts to create an Example with example set to None
I think it’s probably sensible enough to change the default empty_values for JSONField to [None,‘’], which is how I’m working around this for the time being.. But perhaps this should be done in django core?