How to query View in SQLModel
15:20 28 Feb 2022
from typing import Optional

from sqlmodel import Field, Session, SQLModel, create_engine, select

class HeroTeamView(SQLModel):
    name: str
    secret_name: str
    age: Optional[int] = None

sqlite_file_name = "my.db"
db_url = f"mysql+mysqldb://{db_user}:{db_password}@{db_host}:{db_port}/{db_name}"
engine = create_engine(db_url, echo=True)
with Session(engine) as session:
   statement = select(HeroTeamView)
   orgs = session.exec(statement)
   print(f"orgs::{orgs}")
   org_list = orgs.fetchall()

I have a view (let's say HeroTeamView) created in MySQL DB. I want to read this. This view is essentially a left join of Hero and Teams table ioined on Hero.Id.

As shown in example above, as soon as I try to select this view I get error:

HeroTeamView is not a 'SQLModelMetaclass' object is not iterable

How to access rows created by view?

I don't want to use Hero and Team tables directly to write a select query as there are multiple tables and joins in real world problem for me. Using Views provides me some obvious benefits like mentioned here.

mysql sqlalchemy mysql-python sqlmodel