django postgresql json字段架构验证 [英] django postgresql json field schema validation

查看:89
本文介绍了django postgresql json字段架构验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有 JSONField (django.contrib.postgres.fields.JSONField)的Django模型
有什么方法可以验证模型数据一个json模式文件?

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?

(预保存)

类似 my_field = JSONField(schema_file = my_schema_file)

推荐答案

我使用 jsonschema 以便执行此操作(Django 1.11,Python 3.6)。

I wrote a custom validator using jsonschema in order to do this (Django 1.11, Python 3.6).

project / validators.py

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

proj ect / app / models.py

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

这篇关于django postgresql json字段架构验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆