0

I'm building a flask application and need an dict from my database model. The query should filter by user_ids and only query a few rows. I guess the best way is to filter the rows and the use the internal __dict__ object to return my dict. Currently I know how to filter by ids, but I have no idea how to select specific rows. Users.query.filter(Users.id.in_(user_ids)).all()

the array of rows looks like rows = ["username", "role", "last_seen"]

any ideas how to do that?

davidism
  • 110,080
  • 24
  • 357
  • 317
MOE
  • 729
  • 5
  • 14
  • Perhaps you're looking for https://stackoverflow.com/a/45905714/2681632, https://stackoverflow.com/questions/50995345/select-based-on-column-name-list-in-sqlalchemy, or https://stackoverflow.com/questions/21102412/dynamically-query-a-subset-of-columns-in-sqlalchemy. – Ilja Everilä Jan 02 '19 at 20:09

1 Answers1

4

load_only should do the job:

from sqlalchemy.orm import load_only
rows = ["username", "role", "last_seen"]
session.query(Users).filter(Users.id.in_(user_ids)).options(load_only(*rows)).all()
Dani G
  • 1,112
  • 8
  • 16