django postgresql json field schema validation

半世苍凉 提交于 2020-06-09 17:31:30

问题


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)


回答1:


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)]
    )



回答2:


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.')



回答3:


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)



来源:https://stackoverflow.com/questions/37642742/django-postgresql-json-field-schema-validation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!