Skip to content

How to query View in sqlmodelΒ #258

@mrudulp

Description

@mrudulp

First Check

  • I added a very descriptive title to this issue.
  • I used the GitHub search to find a similar issue and didn't find it.
  • I searched the SQLModel documentation, with the integrated search.
  • I already searched in Google "How to X in SQLModel" and didn't find any information.
  • I already read and followed all the tutorial in the docs and didn't find an answer.
  • I already checked if it is not related to SQLModel but to Pydantic.
  • I already checked if it is not related to SQLModel but to SQLAlchemy.

Commit to Help

  • I commit to help with one of those options πŸ‘†

Example Code

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()

Description

I have a view(Lets say HeroTeamView) created in mysql db. I want to read this. This view is essentially a left join of Hero and Teams table Joined 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

I am not quiet sure I understand how to access rows created by view

Any pointers appreciated

Operating System

Windows

Operating System Details

No response

SQLModel Version

0.06

Python Version

3.9.7

Additional Context

I dont 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

Metadata

Metadata

Assignees

No one assigned

    Labels

    questionFurther information is requested

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions