SQLAlchemy ORM to load specific columns in Model.query

强颜欢笑 提交于 2020-02-06 07:56:53

问题


I am newbie in python/sqlachemy world. I am trying to fetch data from PostgreSQL using sqlachemy in flask, where I need to fetch only selected column instead of streaming all the column from database through network. One of the approach is using session (like below) which is working fine,

session.query(User.user_id, User.name).all()

But for some reason I would like to stick with Model.query method instead of using sessions. So I ended up to use something like below,

User.query.options(load_only(User.user_id, User.name)).all()

Above code snippet doesn't filters the selected column, instead it gives back all the column. It looks like sqlachemy doesn't respects the load_only arguments. Why is that behaviour and any solution to achieve my use case in Model.query instead of using sessions?

My user model looks like below,

class User(db.Model):
    __tablename__ = 'user_info'

    user_id = Column(String(250), primary_key=True)
    name = Column(String(250))
    email = Column(String(250))
    address = Column(String(512))

Version Info

  • Python - 3.7
  • sqlachemy - 1.3.11

Edit 1: Though I added load_only attributes, It is generating the following query,

SELECT user.user_id AS user_user_id, user.name AS user_name, user.email AS user_email, user.address AS user_address FROM user_info

来源:https://stackoverflow.com/questions/59736047/sqlalchemy-orm-to-load-specific-columns-in-model-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!