Tools to convert SQLAlchemy models to Pydantic models

Overview

Pydantic-SQLAlchemy

Test Publish Coverage Package version

Tools to generate Pydantic models from SQLAlchemy models.

Still experimental.

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="[email protected]")
address2 = Address(email_address="[email protected]")
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": "[email protected]", "id": 1, "user_id": 1},
            {"email_address": "[email protected]", "id": 2, "user_id": 1},
        ],
    }

Release Notes

Latest Changes

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.

Comments
  • custom orm instead of model translation?

    custom orm instead of model translation?

    Hi, I had the same problem with maintaining two sets of models and took inspiration from encode/orm (not finished) and ormantic (not maintained) and started ormar that uses encode/databases and sqlalchemy core under the hood, and can be used in async mode. @tiangolo feel free to check it out and let me know if you find it useful!

    answered 
    opened by collerek 4
  • Attempt to exclude columns before determining type

    Attempt to exclude columns before determining type

    I have some tables that I'd like to exclude some fields that don't have a python type in sqlalchemy. I'd like to keep them in my model and process them into pydantic manually after the other fields get processed with this utility, but the exclude logic runs after the determination of the type, so I get a NotImplementedError() regardless of exclusion in this case.

    I'd like to just move the exclusion logic above the type determination, so that this wouldn't occur in my use-case.

    opened by ZachMyers3 4
  • which framework to use for model translation

    which framework to use for model translation

    Hi there,

    thanks for all your efforts in getting this model translation to work! Really appreciated. Upon a quick search (there really seems to be an entire zoo of possible orm's + pydantic + graphene models etc. etc.) I came upon this: https://github.com/kolypto/py-sa2schema From the descriptions and listed examples it seems they are trying to achieve the same thing.

    Now the hard question: which one should I use? Any opinions on pro- & cons?

    Thanks, Carsten

    answered 
    opened by camold 3
  • Do not include defaults in models

    Do not include defaults in models

    :bug: Do not include defaults from SQLAlchemy models in Pydantic models.

    SQLAlchemy defaults are supposed to be generated at insertion/update time, not generated by the Pydantic model before creating a new object/record.

    It's also currently broken, as the default included is a SQLAlchemy object, not an actual default.

    opened by tiangolo 3
  • Can you add `depth` feature?

    Can you add `depth` feature?

    I think that the depth is a useful feature when serializing the model has many relationships like the DRF serializer's depth option

    Other libraries that it has depended on Pydantic

    • https://github.com/vitalik/django-ninja/blob/master/ninja/orm/factory.py#L29
    opened by ehdgua01 1
  • WIP: Add optional model name and only parameter to sqlalchemy_to_pydantic

    WIP: Add optional model name and only parameter to sqlalchemy_to_pydantic

    I went ahead and added the new_model_name parameter to close #51 . Will add tests as well.

    I also added an only field, that allows the reverse from exclude: only the mentioned fields will be included.

    I am also thinking to add a class that does something similar. Basically, you would inherit from it set what model you want to use (similar to Django's Meta class for e.g. views) and which fields and in the constructor it calls the sqlalchemy_to_pydantic function (using the new class name as model name) and creates the schema.

    investigate 
    opened by saschahofmann 3
  • Cannot generate two pydantic models from the same SQLAlchemy model

    Cannot generate two pydantic models from the same SQLAlchemy model

    For the create method of SQL model I need to exclude the id of a model, I'd like to call the sqlalchemy_to_pydantic function twice on the same model for example like this:

    PyUser = sqlalchemy_to_pydantic(User)
    PyUserCreate = sqlalchemy_to_pydantic(User, exclude=['id'])
    

    Now the server and every thing starts just fine but when I try to fetch the openapi.json, I get a keyerror because the first model is not in the model map.

    I think line 36 in main.py is at fault

    pydantic_model = create_model(
            db_model.__name__, __config__=config, **fields  # type: ignore
        )
    

    The db_model.__name__ is the same two times so it must be overwriting some key (Disclaimer: I have no idea about the inner workings of pydantic but it seems to be creating some kind of global map of all models?)

    I suggest to add an optional parameter name to the function and replace that line.

    opened by saschahofmann 0
  • Is this project still maintained?

    Is this project still maintained?

    Hi, I like this package, and personally, I used it twice in my little projects. There are some pull requests (including mine) that are not replied to. Is this project no longer maintained? Thanks.

    opened by bichanna 2
  • What about pydantic_to_sqlalchemy?

    What about pydantic_to_sqlalchemy?

    Using sqlalchemy_to_pydantic helped me a lot, but now I need the other way around. Is it supposed to be part of this library?

    Using SQLModel is no proper alternative to me, because it makes things harder, not easier right now.

    investigate 
    opened by mreiche 2
Releases(0.0.9)
Owner
Sebastián Ramírez
Creator of FastAPI, Typer, SQLModel. 🚀 SSE Forethought ➕ consulting. From 🇨🇴 in 🇩🇪. APIs & tools for data/ML. 🤖 Python, TypeScript, Docker, etc. ✨
Sebastián Ramírez
Comprehensive OpenAPI schema generator for Django based on pydantic

??️ Djagger Automated OpenAPI documentation generator for Django. Djagger helps you generate a complete and comprehensive API documentation of your Dj

null 13 Nov 26, 2022
x-tools is a collection of tools developed in Python

x-tools X-tools is a collection of tools developed in Python Commands\

null 5 Jan 24, 2022
Convert three types of color in your clipboard and paste it to the color property (gamma correct)

ColorPaster [Blender Addon] Convert three types of color in your clipboard and paste it to the color property (gamma correct) How to Use Hover your mo

null 13 Oct 31, 2022
An awesome script to convert the University Of Oviedo web calendar to Google or Outlook calendars.

autoUniCalendar Un script en Python para convertir el calendario de la intranet de la Universidad de Oviedo en un calendario de Outlook o Google Calen

Bimo99B9 14 Sep 28, 2022
Convert-Decimal-to-Binary-Octal-and-Hexadecimal

Convert-Decimal-to-Binary-Octal-and-Hexadecimal We have a number in a decimal number, and we have to convert it into a binary, octal, and hexadecimal

Maanyu M 2 Oct 8, 2021
Convert a .vcf file to 'aa_table.tsv', including depth & alt frequency info

Produce an 'amino acid table' file from a vcf, including depth and alt frequency info.

Dan Fornika 1 Oct 16, 2021
A simple python script to convert Rubber Ducky payloads into AutoHotKey scripts

AHKDuckyReplacer A simple python script to convert Rubber Ducky payloads into AutoHotKey scripts. I have also added a sample payload for testing. I wi

Krizsan0596 5 Sep 28, 2022
A script that convert WiiU BotW mods to Switch

UltimateBoTWConverter A script that convert WiiU BotW mods to Switch. It uses every resource I could find under the sun that allows for conversion, wi

null 11 Nov 8, 2022
A Python script to convert your favorite TV series into an Anki deck.

Ankiniser A Python3.8 script to convert your favorite TV series into an Anki deck. How to install? Download the script with git or download it manualy

null 37 Nov 3, 2022
dta Convert Dict To Attributes!

dta (Dict to Attributes) dta is very small dict (or json) to attributes converter. It is only have 1 files and applied to every python versions.

Rukchad Wongprayoon 0 Dec 31, 2021
Convert .1pux to .csv

1PasswordConverter Convert .1pux to .csv 1Password uses this new export format .1pux, I assume stands for 1 Password User eXport. As of right now, 1Pa

Shayne Hartford 7 Dec 16, 2022
Convert temps in your Alfred search bar

Alfred Temp Converter Convert temps in your Alfred search bar. Download Here Usage: temp 100f converts to Celsius, Kelvin, and Rankine. temp 100c conv

Justin Hamilton 4 Apr 11, 2022
Convert Roman numerals to modern numerals and vice-versa

Roman Numeral Conversion Utilities This is a utility module for converting from and to Roman numerals. It supports numbers upto 3,999,999, using the v

Fictive Kin 1 Dec 17, 2021
Convert text with ANSI color codes to HTML or to LaTeX.

Convert text with ANSI color codes to HTML or to LaTeX.

PyContribs 326 Dec 28, 2022
It is a Blender Tool which can convert the Object Data Attributes in face corner to the UVs or Vertex Color.

Blender_ObjectDataAttributesConvertTool It is a Blender Tool which can convert the Object Data Attributes in face corner to the UVs or Vertex Color. D

Takeshi Chō 2 Jan 8, 2022
Convert your Gyrosco.pe travels to GPX files

gyroscope2gpx This little python joint will do you a favor of taking your "Travel" export from Gyroscope (https://gyrosco.pe) and turn it into a bunch

nick g 4 Oct 2, 2022
Convert Photoshop curves (acv) to xmp presets for Lightroom

acv2xmp Convert Photoshop curves (acv) to Lightroom preset (xmp) acv2xmp.py Basic command prompt that relies on standard library only and can be used

null 5 Feb 6, 2022
UFDR2DIR - A script to convert a Cellebrite UFDR to the original file structure

UFDR2DIR A script to convert a Cellebrite UFDR to it's original file and directo

DFIRScience 25 Oct 24, 2022
Scripts to convert the Ted-MDB corpora into the formats for DISRPT shared task and the converted corpora

Scripts to convert the Ted-MDB corpora into the formats for DISRPT shared task and the converted corpora.

null 1 Feb 8, 2022