tiangolo / pydantic-sqlalchemy

Tools to convert SQLAlchemy models to Pydantic models

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Finding Python types for Columns

jenstroeger opened this issue · comments

Hi, thanks for this function just as I started putting together one of my own. Regarding this code:

python_type: Optional[type] = None
if hasattr(column.type, "impl"):
if hasattr(column.type.impl, "python_type"):
python_type = column.type.impl.python_type
elif hasattr(column.type, "python_type"):
python_type = column.type.python_type
assert python_type, f"Could not infer python_type for {column}"

Have you looked at the typing.get_type_hints() function? Perhaps

else:
    python_types = typing.get_type_hints(db_model)
    python_type = python_types[column.name]

works for you as well?

from sqlalchemy.sql import sqltypes
import typing

...

def python_type_for_column(db_model, column):
# Check if the column type is in SQLAlchemy's type map
if isinstance(column.type, sqltypes.TypeEngine):
python_type = column.type.python_type
else:
python_types = typing.get_type_hints(db_model)
python_type = python_types[column.name]
return python_type