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
  • 5,979
  • 4
  • 43
  • 59
ScandinavianWays
  • 149
  • 2
  • 2
  • 7

1 Answers1

9

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

Person.query.with_entities(Person.name).all()
Sicco
  • 5,979
  • 4
  • 43
  • 59
  • 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