October 26, 2024
Chicago 12, Melborne City, USA
python

Convert sqlalchemy orm model (PostgreSQL Ltree extansion) to pydantic


How could I correctly convert my sqlalchemy ORM model field [using PostgreSQL LTREE extension] to pydantic model or string [to use later in FastAPI]?


I have sqlalchemy and pydantic models:

from sqlalchemy.orm import Mapped, mapped_column
from sqlalchemy_utils import LtreeType  # Postgres LTREE extension

from pydantic import BaseModel

# Sqlalchemy ORM <- Works as expected, fetches data
class ItemORM(Base):
    __tablename__ = 'item'

    id: Mapped[int] = mapped_column(primary_key=True)  # 1
    label: Mapped[str]  # 'Some custom label'
    path: Mapped[str] = mapped_column(LtreeType) # 'A.23', THIS TO BE CONVERTED TO PYDANTIC OR STRING

# Pydantic
class Item(BaseModel):
    model_config = ConfigDict(arbitrary_types_allowed=True) # Allows to use LtreeType type for pydantic

    id: int
    label: str
    path: LtreeType | str

My FastAPI code to fetch data and show it to user:

async get_data():
  with Session() as session:
    db_data = session.query(ItemORM).first() # '[(<ItemORM id='1',label="Label",path="A.21">)]'
    item_dto: Item = Item.model_validate(db_data, from_attributes=True) # <- this generates error

When I try to execute it, it gives error:

item.path.is-instance[LtreeType]
  Input should be an instance of LtreeType [type=is_instance_of, input_value=Ltree('A.23'), input_type=Ltree]
  For further information visit https://errors.pydantic.dev/2.9/v/is_instance_of

item.path.str
  Input should be a valid string [type=string_type, input_value=Ltree('A.23'), input_type=Ltree]
  For further information visit https://errors.pydantic.dev/2.9/v/string_type

I’ve tried different pydantic types – str, None, LTreeType, tried to use validators, bus still success isn’t mine, not able to convert specific database type into string.

How can I achieve that?

Thanks!



You need to sign in to view this answers

Leave feedback about this

  • Quality
  • Price
  • Service

PROS

+
Add Field

CONS

+
Add Field
Choose Image
Choose Video