Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSONField doesn't allow null in Django 3.1

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.

like image 984
Jefferson Avatar asked Feb 06 '26 05:02

Jefferson


1 Answers

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.

like image 162
GProst Avatar answered Feb 09 '26 08:02

GProst



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!