Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

249
Visualizações
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
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda