django postgresql json field schema validation

后端 未结 4 1339
半阙折子戏
半阙折子戏 2021-02-05 09:59

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?

4条回答
  •  情深已故
    2021-02-05 10:22

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

提交回复
热议问题