Skip to content

lotrekagency/django-structured-field

Repository files navigation

Django Structured JSON Field PyPI Codecov GitHub Workflow Status GitHub

This is a Django field that allows you to declare the structure of a JSON field and validate it.

Installation

pip install django-structured-field

Usage

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)

Relationships

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.

Recursion

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'] = []

Foreign Keys

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.

ManyToMany

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

Cache

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.

Contributing

The project is open to contributions, just open an issue or a PR.

Running tests

pip install -r requirements-dev.txt
make test

Running test app

pip install -r requirements-dev.txt
python manage.py migrate
python manage.py runserver

License

This project is licensed under the MIT License - see the LICENSE file for details

Releases

No releases published

Packages

No packages published