6

I'm trying to get all the rows in a table, but only one column. The model looks like this:

class Person:
    id= db.Column(db.String(11), primary_key=True, nullable=False)
    name = db.Column(db.String(255), nullable=False)
    city = db.Column(db.String(255), nullable=False)

I want to get the name column ONLY but I can't find anything on how to do this. I've tried stuff like:

Person.query.get(person.name)

The SQLAlchemy documentation doesn't help at all.

Sicco
  • 6,167
  • 5
  • 45
  • 61
ScandinavianWays
  • 159
  • 2
  • 2
  • 7

1 Answers1

11

You need to use with_entities to specify the column that you want to SELECT:

Person.query.with_entities(Person.name).all()
Sicco
  • 6,167
  • 5
  • 45
  • 61
  • this doesnt work – joe hoeller Sep 15 '21 at 16:50
  • @joehoeller it does work (hence 9 people upvoted it). Could you be more specific as to why you think it doesn't work? Also see the documentation for more info: https://docs.sqlalchemy.org/en/14/orm/query.html#sqlalchemy.orm.Query.with_entities – Sicco Oct 04 '21 at 13:29
  • It doesn't work in sqlalchemy 2.0 – Tiago Fassoni Jul 18 '23 at 16:20
  • @TiagoFassoni, the Query API and the `with_entities` method still exist in SQLAlchemy 2.0 (https://docs.sqlalchemy.org/en/20/orm/queryguide/query.html#sqlalchemy.orm.Query.with_entities). If you use `select` you can use the `with_only_columns` method: https://docs.sqlalchemy.org/en/20/core/selectable.html#sqlalchemy.sql.expression.Select.with_only_columns. – Sicco Jul 24 '23 at 10:10