Querying an attribute list instead of tuples in SQLAlchemy

I request model identifiers and get a list of tuples (int,), not a list of identifiers. Is there a way to directly request an attribute?

result = session.query(MyModel.id).all()

I understand what can be done

results = [r for (r,) in results]

Is it possible for the request to return this form directly, instead of processing it on its own?

+18
source share
3 answers

When passed in ORM tool descriptors, such as a column, each result is a named tuple, even for a single column. You can use the column name in the list comprehension to “smooth” the list (you can refuse the call .all(), iteration also returns objects):

result = [r.id for r in session.query(MyModel.id)]

, for :

result = session.query(MyModel.id)
for id, in result:
    # do something with the id

:

[id for id, in session.query(MyModel.id)]

, id.

+21

, SQLalchemy . sqlalchemy, -, , , @Martijn. Python

zip (seq1 [, seq2 [...]]) → [(seq1 [0], seq2 [0]...), (...)] , i-      .      .

result = session.query(MyModel.id).all()
result = zip(*result)[0]

:

[id1, id2, id3...]

, , ,

[(key11, key21), (key12,key22)]

Zip

[(key11, key12), (key21, key22)]

tupe, MyModel, 0- .

+3
q_stringlist = [q[0] for q in session.query((distinct(Table.column))).all()]                                                        

for Flask SQLAlchemy

q_stringlist = [q[0] for q in db.session.query((distinct(Table.column))).all()]   
0
source

All Articles