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
Rates how pog a word or user is. Not random and does have *some* kind of algorithm to it.

PogRater :D Rates how pogchamp a word is :D A fun project coded by JBYT27 using Python3 Have you ever wondered how pog a word is? Well, congrats, you

an aspirin 2 Jun 25, 2022
IPO Checker for NEPSE

IPO Checker Checks more than one account for an IPO. Usage: ipo_checker.py [-h] --file FILE IPO Checker for a list. optional arguments: -h, --help

Sagar Tamang 4 Sep 20, 2022
Change ACLs for QNAP LXD unprivileged container.

qnaplxdunpriv If Advanced Folder Permissions is enabled in QNAP NAS, unprivileged LXD containers won't start. qnaplxdunpriv changes ACLs of some Conta

1 Jan 10, 2022
A lightweight and unlocked launcher for Lunar Client made in Python.

LCLPy LCL's Python Port of Lunar Client Lite. Releases: https://github.com/Aetopia/LCLPy/releases Build Install PyInstaller. pip install PyInstaller

21 Aug 03, 2022
a simple proof system I made to learn math without any mistakes

math_up a simple proof system I made to learn math without any mistakes 0. Short Introduction test yourself, enjoy your math! math_up is an NBG-based,

양현우 5 Jun 04, 2021
A Python program for calculating the 95%CI for GNSS-derived site velocities

GNSS_Vel_95%CI A Python program for calculating the 95%CI for GNSS-derived site velocities Function_GNSS_95CI.py is a Python function for calculating

<a href=[email protected]"> 4 Dec 16, 2022
Example code for the book Fluent Python, 1st Edition (O'Reilly, 2015)

Fluent Python, First Edition: example code This repository is archived and will not be updated.

Fluent Python 5.4k Jan 09, 2023
A Python program that generates a maze that solves itself using DFS

Maze Generator And Solver Program Purpose: Generates a maze that then solves itself Language: Python and Pygame Algorithm: Randomized DFS / Floodfill

Joshua Liu 1 Jul 25, 2022
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
Ellipitical Curve Table Generator

Ellipitical-Curve-Table-Generator This script generates a table of elliptical po

Nishaant Goswamy 1 Jan 02, 2022
Recreating my first CRUD in python, but now more professional

Recreating my first CRUD in python, but now more professional

Ricardo Deo Sipione Augusto 2 Nov 27, 2021
Shared utility scripts for AI for Earth projects and team members

Overview Shared utilities developed by the Microsoft AI for Earth team The general convention in this repo is that users who want to consume these uti

Microsoft 38 Dec 30, 2022
This is a simple web interface for SimplyTranslate

SimplyTranslate Web This is a simple web interface for SimplyTranslate List of Instances You can find a list of instances here: SimplyTranslate Projec

4 Dec 14, 2022
little proyect to organize myself, but maybe can help someone else

TaskXT 0.1 Little proyect to organize myself, but maybe can help someone else Idea The main idea is to ogranize you work and stuff to do, but with onl

Gabriel Carmona 4 Oct 03, 2021
A sage package for working with circular genomes represented by signed or unsigned permutations

Circular genome tools (cgt) A sage package for working with circular genomes represented by signed or unsigned permutations. It includes tools for con

Joshua Stevenson 1 Mar 10, 2022
kodi addon 115网盘

plugin.video.115 kodi addon 115网盘 插件,需要kodi 18以上版本,原码播放需配合 https://github.com/feelfar/115proxy-for-kodi 使用 安装 HEAD 由于release包尚未释出,可直接下载源代码zip包

109 Dec 29, 2022
DD监控室第一版

DD监控室 运行指南

执明神君 1.2k Dec 31, 2022
Python with braces. Because Python is awesome, but whitespace is awful.

Bython Python with braces. Because Python is awesome, but whitespace is awful. Bython is a Python preprosessor which translates curly brackets into in

1 Nov 04, 2021
The Begin button and menu for the Meadows operating system. The start button for UNIX/Linux.

By: Seanpm2001, Meadows Et; Al. Top README.md Read this article in a different language Sorted by: A-Z Sorting options unavailable ( af Afrikaans Afri

Sean P. Myrick V19.1.7.2 4 Aug 28, 2022
News-app - This is a news web app for reading news from different sources and topics

News-app - This is a news web app for reading news from different sources and topics

1 Feb 02, 2022