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

后端 未结 3 650
梦毁少年i
梦毁少年i 2021-01-04 08:52

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 resu

相关标签:
3条回答
  • 2021-01-04 09:24

    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.

    0 讨论(0)
  • 2021-01-04 09:34

    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 ever user with the given name.

    emails = [r.email for r in db.session.query(my_table.c.email).filter_by(name=name).distinct()]
    
    0 讨论(0)
  • 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())

    0 讨论(0)
提交回复
热议问题