django postgresql json field schema validation

2020-06-03 02:57发布

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?

(pre-save)
Something like my_field = JSONField(schema_file=my_schema_file)

3条回答
等我变得足够好
2楼-- · 2020-06-03 03:42

you could use cerberus to validate your data against a schema

from cerberus import Validator

schema = {'name': {'type': 'string'}}
v = Validator(schema)
data = {'name': 'john doe'}
v.validate(data)  # returns "True" (if passed)
v.errors  # this would return the error dict (or on empty dict in case of no errors)

it's pretty straightforward to use (also due to it's good documentation -> validation rules: http://docs.python-cerberus.org/en/stable/validation-rules.html)

查看更多
Rolldiameter
3楼-- · 2020-06-03 03:56

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, a, b):
        try:
            jsonschema.validate(a, b)
        except jsonschema.exceptions.ValidationError:
            raise django.core.exceptions.ValidationError(
                '%(value)s failed JSON schema check', params={'value': a})

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)]
    )
查看更多
叼着烟拽天下
4楼-- · 2020-06-03 03:57

That's what the Model.clean() method is for (see docs). Example:

class MyData(models.Model):
    some_json = JSONField()
    ...

    def clean(self):
        if not is_my_schema(self.some_json):
            raise ValidationError('Invalid schema.')
查看更多
登录 后发表回答