Reputation: 1093
I want to make a Python (SQLAlchemy) program that takes the ID from a table according to a value.
For example, I have a table like this :
-------------------------------
| ID | Name |
-------------------------------
| 1 | Paul |
-------------------------------
| 2 | Paul |
-------------------------------
| 3 | John |
-------------------------------
And I want to retrieve the IDs where the name is Paul.
The code I was doing was something like this :
list = session.query(Table).filter_by(Name='Paul')
list_id = []
for tuple in list :
list_id.append(tuple.id)
for id in list_id :
print(id)
Is there any much easier solution?
Thanks!
Upvotes: 0
Views: 2785
Reputation: 156138
You don't need the intermediate list to 'hold' the id, if you only use them once, just iterate directly over the query.
for row in session.query(Table).filter_by(Name='Paul'):
print(row.ID)
If you only need the ID, you can arrange for your query to return only that:
for ID in session.query(Table.ID).filter_by(Name='Paul'):
print(ID)
Upvotes: 1