question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

How to query View in sqlmodel

See original GitHub issue

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

Issue Analytics

  • State:open
  • Created 2 years ago
  • Comments:7 (4 by maintainers)

github_iconTop GitHub Comments

2reactions
byrmancommented, Mar 3, 2022

Am curious about whether your solution indeed just works, or if something else is needed.

I created a view in PostgreSQL:

test=# \d+ teamsandheroes
                                View "public.teamsandheroes"
    Column    |       Type        | Collation | Nullable | Default | Storage  | Description 
--------------+-------------------+-----------+----------+---------+----------+-------------
 id           | integer           |           |          |         | plain    | 
 name         | character varying |           |          |         | extended | 
 secret_name  | character varying |           |          |         | extended | 
 age          | integer           |           |          |         | plain    | 
 team_id      | integer           |           |          |         | plain    | 
 team         | character varying |           |          |         | extended | 
 headquarters | character varying |           |          |         | extended | 
View definition:
 SELECT h.id,
    h.name,
    h.secret_name,
    h.age,
    h.team_id,
    t.name AS team,
    t.headquarters
   FROM hero h
     JOIN team t ON t.id = h.team_id;

Queried it like this:

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

DB_URL = "postgresql://postgres:postgres@db:5432/test"
engine = create_engine(DB_URL, echo=True)


class HeroTeamView(SQLModel, table=True):
    __tablename__ = "teamsandheroes"

    team_id: int = Field(primary_key=True)
    id: int = Field(primary_key=True)
    name: str
    secret_name: str
    age: int
    team: str
    headquarters: str


def main():
    with Session(engine) as session:
        results = session.exec(select(HeroTeamView))
        for result in results:
            print(result)


if __name__ == "__main__":
    main()

And got this output:

id=1 team_id=1 age=30 secret_name='Dive Wilson' headquarters='Sharp Tower' name='Deadpond' team='Preventers'
id=2 team_id=1 age=20 secret_name='Spider-Boy' headquarters='Sharp Tower' name='Toby Maguire' team='Preventers'

__tablename__ = “viewname” (or did you mean __table__ ?)

The latter gave me a runtime error: AttributeError: 'str' object has no attribute 'c'!?

And if it works, why would you not recommend it?

Personally, I would prefer to interact with individual Hero and Team objects in my code, navigating relationships via properties. Such a HeroTeamView doesn’t feel very natural to me. Counting teams becomes less easy, migration tools might complain, etc. But there might be a use case for this, for example when you don’t have permissions on the individual tables but are allowed to query the view.

0reactions
antontcommented, Mar 7, 2022

Right-o, thanks for the info @byrman . We’ve been also happy with relationships, have not planned multi table views.

We looked into using a view to implement the trashcan pattern for a kind of soft delete, like in https://michaeljswart.com/2014/04/implementing-the-recycle-bin-pattern-in-sql/

After some consideration, we didn’t try views (yet), but have just now deleted==None checks in queries and relationships. We’ll see whether stick with that or start using a view later.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Read Data - SELECT - SQLModel
Let's now see how to read data from the database! ... Before writing Python code let's do a quick review of how querying...
Read more >
How to query View in sqlmodel - Stack Overflow
from typing import Optional from sqlmodel import Field, Session, SQLModel, create_engine, select class HeroTeamView(SQLModel): name: str ...
Read more >
Using the SQL Model Classes | Qt SQL 6.4.1 - Qt Documentation
This is explained in detail in the Presenting Data in a Table View section. ... QSqlQueryModel offers a read-only model based on an...
Read more >
SQL models - dbt Developer Hub
When you execute dbt run , dbt will build this as a view named ... What happens if the SQL in my query...
Read more >
Get Information About a View - SQL Server | Microsoft Learn
Specifies that additional options for views based on aggregate queries are available. Output All Columns Shows whether all columns are returned ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found