This is a Django field that allows you to declare the structure of a JSON field and validate it.
pip install django-structured-field
from django.db import models
from structured.fields import StructuredJSONField
from structured.pydantic.models import BaseModel
# Define this schema as you would do with a Pydantic model
class MySchema(BaseModel):
name: str
age: int = None
def init_data():
return MySchema(name='')
# Create a model with a StructuredJSONField with the schema you defined
class MyModel(models.Model):
structured_data = StructuredJSONField(schema=MySchema, default=init_data)
This field supports relationships between models, you can define them in your schema and they will be treated as normal django relationships. It also supports recursive schemas.
You can define recursive schemas by declaring the attribute type as a string:
from typing import Optional, List
class MySchema(BaseModel):
name: str
age: int = None
parent: Optional['MySchema'] = None
relateds: List['MySchema'] = []
You can also define model relationships in your schema:
from structured.pydantic.fields import ForeignKey
class MySchema(BaseModel):
name: str
age: int = None
parent: ForeignKey['MyModel'] = None
This will treat the parent field as a normal django ForeignKey.
If you need a ManyToMany relationship, you can use the ManyToMany
field:
from structured.pydantic.fields import QuerySet
class MySchema(BaseModel):
name: str
age: int = None
parents: QuerySet['MyModel']
To prevent the field from making multiple identical queries a caching technique is used. The cache is still a work in progress, please open an issue if you find any problem.
The project is open to contributions, just open an issue or a PR.
pip install -r requirements-dev.txt
make test
pip install -r requirements-dev.txt
python manage.py migrate
python manage.py runserver
This project is licensed under the MIT License - see the LICENSE file for details