Tania
Tania

Reputation: 1925

SQLALchemy query all() but get specific fields in list

I have this select statement where I get all ids for a particular name: select name from table1 where id=100;

var1=DBSession.query(table1).filter(table1.id==100).first().name

This returns me with just the first name value for the id 100. However, My query results multiple names and I have to use the all clause like this

varlist=DBSession.query(table1).filter(table1.id==100).all()

Then I am trying to access name from varlist like

for i in varlist:
    otherlist.append(varlist.name)

because this query doesnt put all names in the list:

varlist=DBSession.query(table1).filter(table1.id==100).all().name

Can someone tell me how to get names from .all() directly into "varlist" without using an intermediate list?

Upvotes: 0

Views: 1047

Answers (2)

Tania
Tania

Reputation: 1925

Slightly modifying @Jared's result to make this look better with .all():

namelist=[n.name for n in DBSession.query(table1).filter(table1.id==100).all()] also works. Thank you Jared.

Upvotes: 0

Jared
Jared

Reputation: 26427

The all() method is simply syntactic sugar for calling list on the query. So since you want a single column and not the entity, something like this should work,

names = [name for name, in DBSession.query(table1.name).filter(table1.id == 100)]

Upvotes: 2

Related Questions