Skip to main content

Tools to convert Django ORM models to Pydantic models

Project description

dantico

Tools to convert Django ORM models to Pydantic models.

GitHub Actions (Test) GitHub Actions (Publish) PyPI Supported Python Versions PyPI Supported Django Versions PyPI version

The key features are:

  • Custom Field Support: Create Pydantic Schemas from Django Models with default field type validations out of the box.

  • Field Validator: Fields can be validated with model_validator just like Pydantic validator or root_validator.

Requirements

  • Python 3.6+
  • Django 2.2+
  • Pydantic 1.6+

Installation

pip install dantico

Usage

Here are a few examples of what you can do with Dantico:

Field Validator

model_validator(*args, **kwargs) is a substitute for Pydantic validator used for pre and post fields validation. Their functionalities are the same. More information can be found here.

from django.contrib.auth import get_user_model
from dantico import ModelSchema, model_validator

UserModel = get_user_model()


class CreateUserSchema(ModelSchema):
    class Config:
        model = UserModel
        # Fields to include, by default include all the fields
        # from the Django model
        include = ["username", "email", "password"]

    @model_validator("username")
    def validate_unique_username(cls, value_data: str) -> str:
        if UserModel.objects.filter(username__icontains=value_data).exists():
            raise ValueError("Username exists")
        return value_data

Generate schema instance

You can generate a schema instance from your django model instance using from_orm(cls, obj: Any)

from typings import Optional
from django.contrib.auth import get_user_model
from dantico import ModelSchema, model_validator

UserModel = get_user_model()

new_user = UserModel.objects.create_user(
    username="Max",
    email="max@winoutt.com",
    password="password",
    first_name="Max",
    last_name="Shapira",
)


class UserSchema(ModelSchema):
    class Config:
        model = UserModel
        # Include all the fields from a model except 'password' field
        exclude = ["password"]

schema = UserSchema.from_orm(new_user)

print(schema.json(indent=2)
{
    "id": 1,
    "first_name": "Max",
    "last_name": "Shapira",
    "email": "max@winoutt.com",
    "username": "Max",
}

From ModelSchema to Django Model

You can transfer data from your ModelSchema to Django Model instance using apply(self, model_instance, **kwargs). The apply function uses Pydantic model .dict function, dict function filtering what can be passed as kwargs to the .apply function.

For more information, check out Pydantic model export.

from typings import Optional
from django.contrib.auth import get_user_model
from dantico import ModelSchema, model_validator

UserModel = get_user_model()

new_user = UserModel.objects.create_user(
      username="Max",
      email="max@winoutt.com",
      password="password",
  )


class UpdateUserSchema(ModelSchema):
    class Config:
        model = UserModel
        include = ["first_name", "last_name", "username"]
        optional = ["username"]  # 'username' is now optional

schema = UpdateUserSchema(first_name="Max", last_name="Shapira")
schema.apply(new_user, exclude_none=True)

assert new_user.first_name == "Max" # True
assert new_user.username == "Max" # True

License

This project is licensed under the terms of the MIT license.

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

dantico-0.0.5.tar.gz (21.8 kB view details)

Uploaded Source

Built Distribution

dantico-0.0.5-py3-none-any.whl (15.6 kB view details)

Uploaded Python 3

File details

Details for the file dantico-0.0.5.tar.gz.

File metadata

  • Download URL: dantico-0.0.5.tar.gz
  • Upload date:
  • Size: 21.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: python-requests/2.27.1

File hashes

Hashes for dantico-0.0.5.tar.gz
Algorithm Hash digest
SHA256 9f54099f287c03115ed8248cb3f14f07ab68d2755d7d70c7246672a20c129789
MD5 e09b43b39b54517ef02abe9f4d2164da
BLAKE2b-256 81286e9c66a70d94659c6e4d28047b125ff957644b138de9211e189a7e861c09

See more details on using hashes here.

File details

Details for the file dantico-0.0.5-py3-none-any.whl.

File metadata

  • Download URL: dantico-0.0.5-py3-none-any.whl
  • Upload date:
  • Size: 15.6 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: python-requests/2.27.1

File hashes

Hashes for dantico-0.0.5-py3-none-any.whl
Algorithm Hash digest
SHA256 c6b22cd95d3091ffb28195a164d364e34f5fec94678333c6573f7f01e4c65772
MD5 8f1053801dc8f86e63de0b82ac7aee30
BLAKE2b-256 6dcf5c66dc521e6ad77a4c4725551c3dd37127a572af3fc0452f94e31747fec8

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page