SQLAlchemy Query to retrieve simple table join

tech kamar
Jul 5, 2024

We have 2 classes

class Item(Base):
__tablename__ = "item"
id = mapped_column(Integer, primary_key=True)
name = mapped_column(String)
category = mapped_column(String)

class Order(Base):
__tablename__ = "order"
id = mapped_column(Integer, primary_key=True)
item_id = mapped_column(Integer, ForeignKey("item.id"))
date = mapped_column(String)

Now Query to get data and print them

def retrieve(db_session):
result = db_session.query(Item,Order).join(Order).all()
for item, order in result:
print(f"Item id = {item.id}, name = {item.name}, category = {item.category} | Order id = {order.id}, item_id = {order.id}")

Once we execute retrieve method by passing db_session object we get the result

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

No responses yet

Write a response

Recommended from Medium

Lists

See more recommendations