lurker lurker - 26 days ago 7
Python Question

How to get all values from same column?

I am developing web framework using python. below is my database. this database name is fruit.

name price
----- -----
apple $2
pear $2
grape $4


I am using SQLAlchemy. so class name is Fruit. What should I write to make result below list ..? I want to get values from 'name' column.

['apple', 'pear', 'grape']

and is there any way to execute SQL query directly ..?

sql_query = 'SELECT name FROM Fruit'
Fruit.query.execute(<sql_query>)

Answer

Assuming you have a model called Fruit, to make the database send us only the column(s) you want instead of pulling everything and then filtering the field you want in Python, you can use:

for fruint_name in session.query(Fruit.name):
     # do something with fruit_name

If you don't want duplicates you can use:

for fruint_name in session.query(Fruit.name).distinct():
     # do something with fruit_name
Comments