5

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>)
lurker
  • 309
  • 2
  • 7

2 Answers2

7

One option:

fruit_names = [fruit.name for fruit in Fruit.query.all()]
Jack
  • 20,735
  • 11
  • 48
  • 48
3

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
bakkal
  • 54,350
  • 12
  • 131
  • 107