pydantic-sqlalchemy

repository·master·Indexed 23 days ago

https://github.com/tiangolo/pydantic-sqlalchemy

An experimental tool to dynamically generate Pydantic models from SQLAlchemy models using the sqlalchemy_to_pydantic function. It allows for the creation of Pydantic schemas that mirror database structures and includes OrmConfig to enable orm_mode for instantiating models from SQLAlchemy ORM objects.

Tokens
1.4K
Snippets
1
Records
7
Agent score
81%

What's inside pydantic-sqlalchemy

  1. Use SQLModel instead of Pydantic-SQLAlchemy

    master
    🚨 WARNING: This project is experimental and has significant limitations regarding autocompletion and inline error reporting. For most use cases, you should use SQLModel instead. SQLModel is a more robustly designed library that solves the same problem (generating Pydantic models from SQLAlchemy models) while providing better developer experience and solving additional related problems.
  2. Generate Pydantic models from SQLAlchemy models using `sqlalchemy_to_pydantic`

    master

    You can dynamically generate Pydantic models from existing SQLAlchemy models using the sqlalchemy_to_pydantic function. This allows you to create Pydantic schemas that mirror your database structure. You can then extend these generated models using standard Pydantic inheritance to include relationships or additional fields.

    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")
    
    # Generate Pydantic models
    PydanticUser = sqlalchemy_to_pydantic(User)
    PydanticAddress = sqlalchemy_to_pydantic(Address)
    
    # Extend generated models to include relationships
    class PydanticUserWithAddresses(PydanticUser):
        addresses: List[PydanticAddress] = []
    
    # Usage with SQLAlchemy ORM objects
    # ... (setup engine and session) ...
    user = db.query(User).first()
    
    # Convert ORM object to Pydantic model
    pydantic_user = PydanticUser.from_orm(user)
    data = pydantic_user.dict()
    
    # Convert ORM object with relationships to extended Pydantic model
    pydantic_user_with_addresses = PydanticUserWithAddresses.from_orm(user)
    data_with_addresses = pydantic_user_with_addresses.dict()
  3. sqlalchemy_to_pydantic signature and parameters

    master

    The sqlalchemy_to_pydantic function has the following signature:

    sqlalchemy_to_pydantic(db_model: Type, *, config: Type = OrmConfig, exclude: Container[str] = []) -> Type[BaseModel]

    Parameters:

    • db_model (Type): The SQLAlchemy model class to convert.
    • config (Type, optional): A Pydantic configuration class. Defaults to OrmConfig (which enables orm_mode = True).
    • exclude (Container[str], optional): A container of strings representing field names to be excluded from the generated Pydantic model. Defaults to an empty list [].
  4. Convert SQLAlchemy models to Pydantic models with sqlalchemy_to_pydantic

    master

    The sqlalchemy_to_pydantic function automates the creation of a Pydantic BaseModel from a SQLAlchemy model. It inspects the SQLAlchemy model's columns, infers their Python types, and handles default values and nullability.

    To use it, pass your SQLAlchemy model class to the function. You can optionally provide a custom configuration class or a list of field names to exclude from the resulting Pydantic model.