SQLAlchemy custom type to automatically serialize/deserialize pydantic models
Project description
SQLAlchemy Pydantic Type
SQLAlchemy Pydantic Type is a Python package that bridges SQLAlchemy and Pydantic by providing a custom SQLAlchemy type for seamless serialization and deserialization of Pydantic models as database column values.
The main goal of this project is to make it easy to store and retrieve complex data structures (such as JSON fields) as Pydantic models in your database tables, with automatic conversion between Python objects and database representations. This is especially useful for APIs or applications where you want strong data validation and type safety using Pydantic, while leveraging SQLAlchemy's ORM capabilities.
For example, if you have an Event table with a meta column of type JSON, you can use BasePydanticType to ensure that when you save a Pydantic model to the database, it is automatically serialized to JSON, and when you load it, it is deserialized back into your Pydantic model. The serialization/deserialization logic can be customized by overriding methods or passing custom callables.
See the examples directory for real-world usage.
Features
- Automatic serialization/deserialization of Pydantic models to/from database columns (e.g., JSON, String).
- Customizable serialization: Override methods or provide custom serializer/deserializer functions.
- Easy integration with SQLAlchemy ORM and Core.
- Type safety: Ensures your database fields are always valid Pydantic models.
- Alembic support: Includes helpers for proper autogeneration of migration scripts.
Example
Here's how you can create a custom type that serializes Pydantic models to and from JSON strings:
from sqlalchemy_pydantic_type import BasePydanticType
from sqlalchemy import String
from pydantic import BaseModel
class PydanticString(BasePydanticType):
"""
Custom type that serializes Pydantic models to JSON strings and
deserializes JSON strings back into Pydantic models.
"""
impl = String
cache_ok = True
def _default_model_serializer(self, model: BaseModel) -> Any:
return model.model_dump_json()
def _default_model_deserializer(self, value: Any | None) -> BaseModel:
return self._pydantic_model_type.model_validate_json(value)
class UserMeta(BaseModel):
roles: list[str]
is_active: bool
class User(Base):
__tablename__ = "users"
id: Mapped[int] = mapped_column(primary_key=True)
meta: Mapped[UserMeta] = mapped_column(PydanticString(UserMeta))
In this example, the meta column will automatically handle conversion between UserMeta Pydantic objects and JSON strings in the database.
Alembic Support
To enable proper migration script generation when using SQLAlchemy Pydantic Type with Alembic, follow these steps:
-
Install the package with Alembic support:
pip install sqlalchemy_pydantic_type[alembic]
-
In your Alembic environment (
env.py), import therender_itemfunction:from sqlalchemy_pydantic_type.alembic import render_item
-
Add the
render_itemargument to allcontext.configure()calls:context.configure( url=url, target_metadata=target_metadata, literal_binds=True, render_item=render_item, # Add this line dialect_opts={"paramstyle": "named"}, )
This ensures that Alembic correctly generates migration scripts for columns using Pydantic types.
For a complete working example, check out the kitchen sink example in the examples directory.
Development
For details on setting up the development environment and contributing, see CONTRIBUTING.md.
Credits
This package was created with The Hatchlor project template.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file sqlalchemy_pydantic_type-0.0.1.tar.gz.
File metadata
- Download URL: sqlalchemy_pydantic_type-0.0.1.tar.gz
- Upload date:
- Size: 6.9 kB
- Tags: Source
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.12.9
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
1be73d4215a129ce28cf1b3e67b75141f661d1ecaeda0fa265272ff2b8fd6528
|
|
| MD5 |
3e043dc71125d574df9911f785ad3a92
|
|
| BLAKE2b-256 |
4bcd823ff85ffc3ebe40a8109d928b19a09f650997e486dd9bdd3a8023d6db78
|
Provenance
The following attestation bundles were made for sqlalchemy_pydantic_type-0.0.1.tar.gz:
Publisher:
build.yml on bartosz121/sqlalchemy-pydantic-type
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
sqlalchemy_pydantic_type-0.0.1.tar.gz -
Subject digest:
1be73d4215a129ce28cf1b3e67b75141f661d1ecaeda0fa265272ff2b8fd6528 - Sigstore transparency entry: 245640488
- Sigstore integration time:
-
Permalink:
bartosz121/sqlalchemy-pydantic-type@54b8d439c51ce497f409a101ca016d0151321b8b -
Branch / Tag:
refs/tags/v0.0.1 - Owner: https://github.com/bartosz121
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
build.yml@54b8d439c51ce497f409a101ca016d0151321b8b -
Trigger Event:
push
-
Statement type:
File details
Details for the file sqlalchemy_pydantic_type-0.0.1-py3-none-any.whl.
File metadata
- Download URL: sqlalchemy_pydantic_type-0.0.1-py3-none-any.whl
- Upload date:
- Size: 6.8 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.12.9
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
b725ef2d61bb51d47f56b0d1a97ec725e38a41ab1d93e80d871f3b17c8b2e986
|
|
| MD5 |
cc6bdaa98bdd4fd4039b4fd13faec7ae
|
|
| BLAKE2b-256 |
d7fbe4d69eda89910c44b2e29e687dad352de650122853d27e4c9f0d789e4b6e
|
Provenance
The following attestation bundles were made for sqlalchemy_pydantic_type-0.0.1-py3-none-any.whl:
Publisher:
build.yml on bartosz121/sqlalchemy-pydantic-type
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
sqlalchemy_pydantic_type-0.0.1-py3-none-any.whl -
Subject digest:
b725ef2d61bb51d47f56b0d1a97ec725e38a41ab1d93e80d871f3b17c8b2e986 - Sigstore transparency entry: 245640489
- Sigstore integration time:
-
Permalink:
bartosz121/sqlalchemy-pydantic-type@54b8d439c51ce497f409a101ca016d0151321b8b -
Branch / Tag:
refs/tags/v0.0.1 - Owner: https://github.com/bartosz121
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
build.yml@54b8d439c51ce497f409a101ca016d0151321b8b -
Trigger Event:
push
-
Statement type: