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
Collapse a set of redundant kmers to use IUPAC degenerate bases

kmer-collapse Collapse a set of redundant kmers to use IUPAC degenerate bases Overview Given an input set of kmers, find the smallest set of kmers tha

Alex Reynolds 3 Jan 06, 2022
Xbps-install wrapper written in Python that doesn't care about case sensitiveness and package versions

xbi Xbps-install wrapper written in Python that doesn't care about case sensitiveness and package versions. Description This Python script can be easi

Emanuele Sabato 5 Apr 11, 2022
A module to develop and apply old-style links

Old-Linkage-Dev (OLD) Old Linkage Development is a module to develop and apply old-style links. Old-style links stand for some traditional or conventi

Tarcadia 2 Dec 04, 2021
PhD document for navlab

PhD_document_for_navlab The project contains the relative software documents which I developped or used during my PhD period. It includes: FLVIS. A st

ZOU YAJING 9 Feb 21, 2022
Run PD patches in NRT using Python

The files in this repository demonstrate how to use Pure Data (Pd) patches designed to run in Non-Real-Time mode to batch-process (synthesize, analyze, etc) sounds in series using Python.

Jose Henrique Padovani 3 Feb 08, 2022
Traffic flow test platform, especially for reinforcement learning

Traffic Flow Test Platform Traffic flow test platform, especially for reinforcement learning, named TFTP. A traffic signal control framework that can

4 Nov 07, 2022
Badge-Link-Creater 'For more beautiful profiles.'

Badge-Link-Creater 'For more beautiful profiles.' Ready Badges Prepares the codes of the previously prepared badges for you. Note Click here for more

Mücahit Gündüz 9 Oct 19, 2022
A simple python project which control paint brush in microsoft paint app

Paint Buddy In Python A simple python project which control paint brush in micro

Ordinary Pythoneer 1 Dec 27, 2021
Vaksina - Vaksina COVID QR Validation Checker With Python

Vaksina COVID QR Validation Checker Vaksina is a general purpose library intende

Michael Casadevall 33 Aug 20, 2022
A Python wrapper API for operating and working with the Neo4j Graph Data Science (GDS) library

gdsclient NOTE: This is a work in progress and many GDS features are known to be missing or not working properly. This repo hosts the sources for gdsc

Neo4j 100 Dec 20, 2022
Reactjs web app written entirely in python, using transcrypt compiler.

Reactjs web app written entirely in python, using transcrypt compiler.

Dan Shai 22 Nov 27, 2022
HiSim - House Infrastructure Simulator

HiSim is a Python package for simulation and analysis of household scenarios using modern components as alternative to fossil fuel based ones.

FZJ-IEK3 17 Dec 17, 2022
Timetable scripts for python

Timetable Scripts timetable_to_json: https://beta.elektronplus.pl/timetable classes_taught_by_teacher: a.adam (aa) ['1Tc', '1Td', '3Te', '3Ti', '4Tf',

Elektron++ 2 Jan 02, 2022
Tracking stock volatility.

SP500-highlow-tracking Track stock volatility. Being a useful indicator of the stock price volatility, High-Low gap represents the price range of the

Thong Huynh 13 Sep 07, 2022
A Python Web Application for Checking vaccine slots by pincodes and auto slot booking.

The Dashboard is developed using Bokeh and python 3.5+. This dashboard is useful for you if you are looking for something which will help you to book the vaccine slot once slots become available. Oth

Suraj Deshmukh 10 Jan 23, 2022
Python plugin for Krita that assists with making python plugins for Krita

Krita-PythonPluginDeveloperTools Python plugin for Krita that assists with making python plugins for Krita Introducing Python Plugin developer Tools!

18 Dec 01, 2022
This app converts an pdf file into the audio file.

PDF-to-Audio This app takes an pdf as an input and convert it into audio, and the library text-to-speech starts speaking the preffered page given in t

Ojas Barawal 3 Aug 04, 2021
Statically typed BNF with semantic actions; A frontend of frontend frameworks; Use your grammar everywhere.

Statically typed BNF with semantic actions; A frontend of frontend frameworks; Use your grammar everywhere.

Taine Zhao 56 Dec 14, 2022
Scientific color maps and standardization tools

Scicomap is a package that provides scientific color maps and tools to standardize your favourite color maps if you don't like the built-in ones. Scicomap currently provides sequential, bi-sequential

Thomas Bury 14 Nov 30, 2022
This repository contains all the data analytics projects that I've worked on in python.

93_Python_Data_Analytics_Projects This repository contains all the data analytics projects that I've worked on in python. No. Name 01 001_Cervical_Can

Milaan Parmar / Милан пармар / _米兰 帕尔马 267 Jan 06, 2023