Files
pydantic/docs/examples/models_orm_mode_reserved_name.py
T
Pierre Bonneau 21b8e22214 Renaming BaseModel (#4758)
Hello

BaseModel is an import from pydantic.
Using that same name for the Base from sqlachemy can be misleading, and not aligned to the other examples.

I therefore suggest to use the same naming that the other example.

Pierre
2022-11-17 10:01:56 +00:00

31 lines
683 B
Python

import typing
from pydantic import BaseModel, Field
import sqlalchemy as sa
from sqlalchemy.ext.declarative import declarative_base
class MyModel(BaseModel):
metadata: typing.Dict[str, str] = Field(alias='metadata_')
class Config:
orm_mode = True
Base = declarative_base()
class SQLModel(Base):
__tablename__ = 'my_table'
id = sa.Column('id', sa.Integer, primary_key=True)
# 'metadata' is reserved by SQLAlchemy, hence the '_'
metadata_ = sa.Column('metadata', sa.JSON)
sql_model = SQLModel(metadata_={'key': 'val'}, id=1)
pydantic_model = MyModel.from_orm(sql_model)
print(pydantic_model.dict())
print(pydantic_model.dict(by_alias=True))