I'm trying to use a JSONField in Django, sometimes I need it be null so I defined it with null=True, blank=True, but when I'm validating with the Serializer I'm getting my_data: [This field can't be null]. Here is my code:
models.py
class MyModel(models.Model):
my_data = models.JSONField('data', null=True, blank=True, editable=False)
serializer.py
class MyModelSerializer(serializers.ModelSerializer):
my_data = serializers.JSONField()
class Meta:
model = MyModel
fields = '__all__'
view.py
def save_my_data(self, request):
info['my_data'] = None
serializer = serializers.MyModelSerializer(data=info)
# validate the data
print( serializer.is_valid() ) #returns False
print( serializer.errors ) #returns my_data: [This field can't be null]
Any suggestions about this? Thanks in advance.
Set allow_null=True in your serializer:
class MyModelSerializer(serializers.ModelSerializer):
my_data = serializers.JSONField(allow_null=True)
In DRF allow_null is False by default, even if your model is configured to accept null.
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