I have a django model with a JSONField
(django.contrib.postgres.fields.JSONField)
Is there any way that I can validate model data against a json schema file?
I wrote a custom validator using jsonschema in order to do this (Django 1.11, Python 3.6).
project/validators.py
import django
from django.core.validators import BaseValidator
import jsonschema
class JSONSchemaValidator(BaseValidator):
def compare(self, input, schema):
try:
jsonschema.validate(input, schema)
except jsonschema.exceptions.ValidationError:
raise django.core.exceptions.ValidationError(
'%(value)s failed JSON schema check', params={'value': input})
project/app/models.py
from django.db import models
from django.contrib.postgres.fields import JSONField
from project.validators import JSONSchemaValidator
MY_JSON_FIELD_SCHEMA = {
'schema': 'http://json-schema.org/draft-07/schema#',
'type': 'object',
'properties': {
'my_key': {
'type': 'string'
}
},
'required': ['my_key']
}
class MyModel(models.Model):
my_json_field = JSONField(
default=dict,
validators=[JSONSchemaValidator(limit_value=MY_JSON_FIELD_SCHEMA)]
)