Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get a list of values of one column from the results of a query

I have a User model where users can have the same name. I want to get the email addresses of all the users with a given name. However, I have to do result[0].email on the result of the query to get just the email for a row. I could do this with a for loop, but is there a way to just get the list of one field without having to do this every time?

my_result = db.session.query(my_table).filter_by(name=name)
emails = []
for r in my_result:
    emails.append(r.email)
like image 505
Pav Sidhu Avatar asked Aug 05 '15 20:08

Pav Sidhu


People also ask

How to find the sum of all the values in a column in SQL?

The SUM() function returns the total sum of a numeric column.

What is SELECT list in SQL?

The SELECT list names the columns, functions, and expressions that you want the query to return. The list represents the output of the query.

How do I SELECT a column in SQLAlchemy?

SQLAlchemy Core The already created students table is referred which contains 4 columns, namely, first_name, last_name, course, score. But we will be only selecting a specific column. In the example, we have referred to the first_name and last_name columns. Other columns can also be provided in the entities list.


3 Answers

No, there's not really a way around the fact that SQLAlchemy queries return a list of dicts. If you want a specific set of fields, you can query for just those fields, but if you want a list of one field, you'll have to extract it from the result. The following example gets a list of the unique emails for every user with the given name.

emails = [r.email for r in db.session.query(my_table.c.email).filter_by(name=name).distinct()]
like image 138
davidism Avatar answered Oct 23 '22 08:10

davidism


There is a way to return specific columns from a filter_by query using the values method. As follows:

 emails = [r[0] for r in db.session.query(my_table).filter_by(name=name).values('email')]

or:

 emails = [r[0] for r in User.query.filter_by(name=name).values('email')]

values() takes any number of field names as parameters and returns a generator that has tuples with each value from each field name. Using a list comprehension to take the first item of that tuple emails will then be a list of plain string email addresses.

like image 28
Martlark Avatar answered Oct 23 '22 07:10

Martlark


Just to keep a record, I like a wrapper with this function in my common use lib:

def flat_list(l): return ["%s" % v for v in l]

Then:

flat_list(db.session.query(Model.column_attribute).all())

like image 1
Isaque Profeta Avatar answered Oct 23 '22 08:10

Isaque Profeta