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.
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:
Most helpful comment
Awesome, thank you! I did have the
orm_mode = Trueconfiguration (forgot to type it in) but was definitely not usingfrom_orm, which is the key. Thanks again!