2

I have a Django Model which looks something like this:

class Foo:
  data = JSONField(encoder=DjangoJSONEncoder, default=dict)

And I have the corresponding serializer for it which is pretty basic:

class FooSerializer(BaseSerializer):

  class Meta:
    model = models.Foo
    fields = '__all__'

What I want to do is to have some validations for that JSON field in the serializer. I tried doing this via overriding the validate and create functions but in both cases the value for attrs.data or validated_data.data is None.

The weird part is that if I create the same validations in the pre-save or post-save signals then the instance.data value is not None and actually has the value I'm passing in the request.

I'm wondering if I'm doing something wrong or does DRF not support doing validations for JSON fields in the serializer and just expect you to do it in the signals. That seems kinda wrong.

Vishal Rao
  • 872
  • 1
  • 7
  • 18

1 Answers1

1

You can pass custom validators as arugment like

 class Foo(models.Model):
     data = JSONField(encoder=DjangoJSONEncoder, default=dict,validators=[validate_json])

or simple in TextField like

class Foo(models.Model):
    data = models.TextField(default={},validators=[validate_json])

and define validate_json as

import json
from rest_framework.serializers import ValidationError
def validate_json(value):
    #your custom validations here
    try:
        json.loads(value) 
    except:
        raise ValidationError(u'%s is not an Valid Json - ' % value)
Yugandhar Chaudhari
  • 3,831
  • 3
  • 24
  • 40