Fastapi: [QUESTION] How to generate a pydantic model from a sqlalchemy model?

Created on 20 Dec 2019  路  3Comments  路  Source: tiangolo/fastapi

Description

Given a SQLAlchemy declarative model

Base = declarative_base()

class EntityORM(Base):
    __tablename__ = "entities"

    id = Column(Integer, primary_key=True)
    name = Column(String, nullable=False)
    version = Column(Integer, nullable=False)

and a pydantic model:

class Entity(BaseModel):
    id: int
    name: str
    version: int

How do I go from one to the other, like:

e1 = EntityORM(name="foo", version=42)
e2 = Entity(e1) # exception: TypeError: __init__() takes 1 positional argument but 2 were given

Somehow FastAPI is doing it with response_model, how can I do that myself? I'd like to always reason about Pydantic models in my code rather than intersperse ORM objects.

question

Most helpful comment

Awesome, thank you! I did have the orm_mode = True configuration (forgot to type it in) but was definitely not using from_orm, which is the key. Thanks again!

All 3 comments

You have to add orm_mode to the config:

class Entity(BaseModel):
    id: int
    name: str
    version: int

    class Config:
        orm_mode = True

then you can do

entity_orm = EntityORM(...)
entity = Entity.from_orm(entity_orm)

This is essentially what FastAPI does, by way of the validate_model function from pydantic (if I recall correctly...).

Awesome, thank you! I did have the orm_mode = True configuration (forgot to type it in) but was definitely not using from_orm, which is the key. Thanks again!

Thanks for the help here @dmontagu ! :clap: :bow:

Thanks for reporting back and closing the issue @f0ff886f :+1:

Was this page helpful?
0 / 5 - 0 ratings