1. Anuncie Aqui ! Entre em contato fdantas@4each.com.br

[Python] Select Multiple Columns Efficiently in SQLModel

Discussão em 'Python' iniciado por Stack, Setembro 12, 2024.

  1. Stack

    Stack Membro Participativo

    I'm using SQLModel, which is a wrapper around SQLAlchemy.

    The data model includes:

    class Line(SQLModel, table = True):
    id: int | None = Field(default = None, primary_key = True)
    name: str

    class Product(SQLModel, table = True):
    id: int | None = Field(default = None, primary_key = True)
    line_id: int | None = Field(default = None, foreign_key = 'line.id')
    myob_uid: str
    myob_name: str
    weight: float


    An example query that selects a subset of columns from both tables:

    query = select(Product.id, Product.weight, Line.name)\
    .join(Line)


    Notice the repetition of table name in the select statement. In SQLAlchemy we can do this:

    select(Product.c['id','weight'], Line.c['name'])


    However the c attribute is not available in SQLModel.

    Is there a way to subset a table by multiple columns without repeating the name?

    This is a pedantic request. However writing DRY queries is important as they become large and complex.

    I've tried both the following however they aren't as elegant for readability:

    • Aliasing the tables to a letter (p or l for example).
    • select(*[getattr(Product, x) for x in ['id','weight']], Line.name).

    Continue reading...

Compartilhe esta Página