Member-only story
Getting Started with SQLAlchemy ORM — Data Fetching (3/5)
Many things work the same in ORM as in Core. One thing is different, and that is that we work with a session instead of the connection.execution method.
Getting by id
If we want to fetch a user by id, we have two options. We can use session.query
and session.get
.
Note that the get method is available directly on the session, and it requires sending the Todo class and the primary key.
from sqlalchemy import create_engine, Column, Integer, Text
from sqlalchemy.orm import Session, DeclarativeBase
class Base(DeclarativeBase):
pass
class Todo(Base):
__tablename__ = "todos"
id = Column(Integer, primary_key=True)
label = Column(Text, nullable=False)
status = Column(Text, nullable=False)
# Base.metadata.drop_all(engine)
# Base.metadata.create_all(engine)
todos = [
Todo(label="Walk a dog", status="doing"),
Todo(label="Shopping", status="in_progress"),
]
with Session(engine) as session:
# session.add_all(todos)
# session.commit()
result = (
session.get(Todo, 1)
)
print(result.id, result.label, result.status) # 1 Walk a dog doing
If we do not want to use the primary key or want to search on another column, we can use the where
method. In this case, for example, we must use the…