Skip to main content

Tools to convert SQLAlchemy models to Pydantic models

Project description

Pydantic-SQLAlchemy

Test Publish Coverage Package version

Tools to generate Pydantic models from SQLAlchemy models.

Still experimental.

🚨 WARNING: Use SQLModel instead 🚨

SQLModel is a library that solves the same problem as this one, but in a much better way, also solving several other problems at the same time.

This project was to solve some simple use cases, to generate dynamic Pydantic models from SQLAlchemy models. But the result cannot be used very well in code as it doesn't have all the autocompletion and inline errors that a Pydantic model would have.

This was a very simple implementation, SQLModel is a much better solution, much better design and work behind it.

For most of the cases where you would use pydantic-sqlalchemy, you should use SQLModel instead.

How to use

Quick example:

from typing import List

from pydantic_sqlalchemy import sqlalchemy_to_pydantic
from sqlalchemy import Column, ForeignKey, Integer, String, create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import Session, relationship, sessionmaker

Base = declarative_base()

engine = create_engine("sqlite://", echo=True)


class User(Base):
    __tablename__ = "users"

    id = Column(Integer, primary_key=True)
    name = Column(String)
    fullname = Column(String)
    nickname = Column(String)

    addresses = relationship(
        "Address", back_populates="user", cascade="all, delete, delete-orphan"
    )


class Address(Base):
    __tablename__ = "addresses"
    id = Column(Integer, primary_key=True)
    email_address = Column(String, nullable=False)
    user_id = Column(Integer, ForeignKey("users.id"))

    user = relationship("User", back_populates="addresses")


PydanticUser = sqlalchemy_to_pydantic(User)
PydanticAddress = sqlalchemy_to_pydantic(Address)


class PydanticUserWithAddresses(PydanticUser):
    addresses: List[PydanticAddress] = []


Base.metadata.create_all(engine)


LocalSession = sessionmaker(bind=engine)

db: Session = LocalSession()

ed_user = User(name="ed", fullname="Ed Jones", nickname="edsnickname")

address = Address(email_address="ed@example.com")
address2 = Address(email_address="eddy@example.com")
ed_user.addresses = [address, address2]
db.add(ed_user)
db.commit()


def test_pydantic_sqlalchemy():
    user = db.query(User).first()
    pydantic_user = PydanticUser.from_orm(user)
    data = pydantic_user.dict()
    assert data == {
        "fullname": "Ed Jones",
        "id": 1,
        "name": "ed",
        "nickname": "edsnickname",
    }
    pydantic_user_with_addresses = PydanticUserWithAddresses.from_orm(user)
    data = pydantic_user_with_addresses.dict()
    assert data == {
        "fullname": "Ed Jones",
        "id": 1,
        "name": "ed",
        "nickname": "edsnickname",
        "addresses": [
            {"email_address": "ed@example.com", "id": 1, "user_id": 1},
            {"email_address": "eddy@example.com", "id": 2, "user_id": 1},
        ],
    }

Release Notes

Latest Changes

0.0.10

Breaking Changes

  • ➖ Drop support for End of Life Python versions 3.8 and 3.9. PR #240 by @tiangolo.

Docs

Internal

0.0.9

  • ✨ Add poetry-version-plugin, remove importlib-metadata dependency. PR #32 by @tiangolo.

0.0.8.post1

  • 💚 Fix setting up Poetry for GitHub Action Publish. PR #23 by @tiangolo.

0.0.8

  • ⬆️ Upgrade importlib-metadata to 3.0.0. PR #22 by @tiangolo.
  • 👷 Add GitHub Action latest-changes. PR #20 by @tiangolo.
  • 💚 Fix GitHub Actions Poetry setup. PR #21 by @tiangolo.

0.0.7

  • Update requirements of importlib-metadata to support the latest version 2.0.0. PR #11.

0.0.6

0.0.5

  • Exclude columns before checking their Python types. PR #5 by @ZachMyers3.

0.0.4

  • Do not include SQLAlchemy defaults in Pydantic models. PR #4.

0.0.3

  • Add support for exclude to exclude columns from Pydantic model. PR #3.
  • Add support for overriding the Pydantic config. PR #1 by @pyropy.
  • Add CI with GitHub Actions. PR #2.

License

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

Project details


Download files

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

Source Distribution

pydantic_sqlalchemy-0.0.10.tar.gz (9.0 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

pydantic_sqlalchemy-0.0.10-py3-none-any.whl (5.9 kB view details)

Uploaded Python 3

File details

Details for the file pydantic_sqlalchemy-0.0.10.tar.gz.

File metadata

  • Download URL: pydantic_sqlalchemy-0.0.10.tar.gz
  • Upload date:
  • Size: 9.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for pydantic_sqlalchemy-0.0.10.tar.gz
Algorithm Hash digest
SHA256 4f44afbe6e38d601d325a8f74d9b9a0d3922634570378701e16019afa62f48a3
MD5 f2fca74305953f9ce34293382c0dc2cf
BLAKE2b-256 f2fd5f5c5c86194090554fdf45aa3c8816e4ebe0af5e7897effb82fbc8cd4fde

See more details on using hashes here.

Provenance

The following attestation bundles were made for pydantic_sqlalchemy-0.0.10.tar.gz:

Publisher: publish.yml on tiangolo/pydantic-sqlalchemy

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file pydantic_sqlalchemy-0.0.10-py3-none-any.whl.

File metadata

File hashes

Hashes for pydantic_sqlalchemy-0.0.10-py3-none-any.whl
Algorithm Hash digest
SHA256 3e06d898328a836180cb8ddcb02ef1d9e18020a1ce073dd44862b0a9a9eef8c7
MD5 25d5517db62d780a7ad7c031ee40d739
BLAKE2b-256 bfa120c5098ba0ef7f796e084b3ab86834ec50eff6eac43cc15112f18d6af54b

See more details on using hashes here.

Provenance

The following attestation bundles were made for pydantic_sqlalchemy-0.0.10-py3-none-any.whl:

Publisher: publish.yml on tiangolo/pydantic-sqlalchemy

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

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