pydantic-sqlalchemy
repository·master·Indexed 23 days ago
https://github.com/tiangolo/pydantic-sqlalchemyAn 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.
What's inside pydantic-sqlalchemy
- 🚨 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.
Generate Pydantic models from SQLAlchemy models using `sqlalchemy_to_pydantic`
masterYou can dynamically generate Pydantic models from existing SQLAlchemy models using the
sqlalchemy_to_pydanticfunction. 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()sqlalchemy_to_pydantic
masterThesqlalchemy_to_pydanticfunction takes a SQLAlchemy model class as an argument and returns a new Pydantic model class that represents the fields defined in that SQLAlchemy model.sqlalchemy_to_pydantic signature and parameters
masterThe
sqlalchemy_to_pydanticfunction 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 toOrmConfig(which enablesorm_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[].
Convert SQLAlchemy models to Pydantic models with sqlalchemy_to_pydantic
masterUse thesqlalchemy_to_pydanticfunction to automatically create a Pydantic model class from an existing SQLAlchemy model. This is useful for generating Pydantic schemas that match your database structure without manual re-definition.Convert SQLAlchemy models to Pydantic models with sqlalchemy_to_pydantic
masterThe
sqlalchemy_to_pydanticfunction automates the creation of a PydanticBaseModelfrom 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.
Use OrmConfig for SQLAlchemy integration
masterTheOrmConfigclass is a specialized PydanticBaseConfigthat setsorm_mode = True. This is required when you want to use Pydantic's.from_orm()method to instantiate models directly from SQLAlchemy ORM objects.