Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

248
Views
SQL Alchemy mapper for multi table join

I have three tables:

Farmer = Table(
    "farmer",
    metadata,
    Column("farmer_id", UUID(), primary_key=True, default=uuid.uuid4, unique=True, nullable=False)
)

Fruit = Table(
    "fruit",
    metadata,
    Column("fruit_id", UUID(), primary_key=True, default=uuid.uuid4, unique=True, nullable=False),
    Column("farmer_id",  UUID(), ForeignKey("farmer.farmer_id"), nullable=False)
)

Vegetable = Table(
    "vegetable",
    Column("vegetable_id", UUID(), primary_key=True, default=uuid.uuid4, unique=True, nullable=False),
    Column("farmer_id",  UUID(), ForeignKey("farmer.farmer_id"), nullable=False)
)

A Farmer can have 0-n Fruits and/or 0-n Vegetables.

Given a farmer_id I want to get the details of the farmer (there are other columns left out of the above for brevity) plus all the details of all of the fruits/vegetables they might grow, the SQL would be:

SELECT *
FROM farmer LEFT OUTER JOIN fruit ON farmer.farmer_id = fruit.farmer_id LEFT OUTER JOIN vegetable ON farmer.farmer_id = vegetable.farmer_id WHERE farmer_id = ?;

And I can replicate that with a SQLAlchemy core query like so:

query = select(
    [Farmer, Fruit, Vegetable]
).select_from(
  Farmer.join(
      Fruit, Farmer.c.farmer_id == Fruit.c.farmer_id,
      isouter=True
  ).join(
      Vegetable, Farmer.c.farmer.id == Vegetable.c.farmer_id,
      isouter=True
  )
).where(
    Farmer.c.farmer_id == ?
)

What I am unsure about is how to map the result of this query into objects. I seem to need to use a mapper and some classes but I am not sure how to do this with multiple joins.

How do I write a mapper to take the result of the above query and generate an object graph along the lines of:

class FarmerObject:
    fruits = [...]
    vegetables = [...]
over 4 years ago · Santiago Trujillo
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!