django postgresql json field schema validation

后端 未结 4 1333
半阙折子戏
半阙折子戏 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:19

    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)

提交回复
热议问题