How to build a SQL query with PyPika by iterating over a list?

945 Views Asked by At

Is it possible to build a SQL query using PyPika using a list to select fields? Attempting something similar to the below to build a SQL query.

from pypika import Query, Table
customers = Table('data_table')
field_list = ['user', 'age']
sql = Query.from_(customers).select(field_list).where(
    (customers.start_time >= start_time) &
    (customers.end_time <= end_time) &
    (customers.pair == pair)
)
1

There are 1 best solutions below

0
Benjamin Dubreu On

I believe this should work:

from pypika import Query, Table,Field
customers = Table('data_table')
field_list = [Field(c) for c in ['user', 'age']]
sql = Query.from_(customers).select(*field_list).where(
    (customers.start_time >= start_time) &
    (customers.end_time <= end_time) &
    (customers.pair == pair)
)

Note the unpacking of field_list with * ;)