3

I'm using query like this: user = User.query.options(load_only("email", "name")).filter(and_(User.id == id, User.status == 1)).first()

I want to get only email and name column as an User object. But it returns all columns. I can't find any solutions. Can anybody help? Thanks

davidism
  • 121,510
  • 29
  • 395
  • 339
GB0
  • 39
  • 3
  • Your `user` data model is defined (as the underlying table is) to have all fields. I think this is intended behavior to ensure model/data integrity. – jbndlr Feb 03 '17 at 08:36
  • Maybe http://docs.sqlalchemy.org/en/latest/orm/query.html#sqlalchemy.orm.query.Query.values will do it ? – vovaminiof Feb 03 '17 at 09:57
  • 1
    How do you know it returns all columns? Remember, SQLAlchemy lazy loads any columns on access if it's not loaded. – univerio Feb 03 '17 at 17:12
  • Sorry for posting in old question, I am suffering from the same. Is there is any solution for this without using database session method or jbndlr's comment is the answer? @univerio Yes, it returns all the column, I am able to confirm in my use case. – Jaya Ananthram Jan 13 '20 at 16:09
  • @JayaAnanthram How have you confirmed it? Just saying "it doesn't work" is not much to go on. I'd recommend posting a new question with details about your specific situation as it's likely that either your situation is not the same as OP's or whatever you did to confirm it is incorrect. – univerio Jan 16 '20 at 06:57
  • @univerio Yes I raised it already [here](https://stackoverflow.com/questions/59736047/sqlalchemy-orm-to-load-specific-columns-in-model-query) – Jaya Ananthram Jan 16 '20 at 14:22

1 Answers1

1

If you're using a database session, you can simply specify the columns directly.

session.query(User.email, User.name).filter(and_(User.id == id, User.status == 1)).first()

dizzyf
  • 3,263
  • 19
  • 29