【问题标题】:querying and selecting specific column in SQLAlchemy在 SQLAlchemy 中查询和选择特定列
【发布时间】:2014-06-03 09:59:20
【问题描述】:

如何从查询中选择特定列。 例如,仅来自以下位置的照片的用户名和大小:

class User(Base):
    __tablename__ = 'user'
    user_id =      Column(String,   primary_key = True, unique = True)
    real_name =    Column(String,   nullable = True)

class Photo(Base):
    __tablename__ = 'photo'
    url =        Column(String,        primary_key = True, unique = True)
    size =       Column(Integer,       nullable = False)
    ts_taken =   Column(DateTime,      nullable = True)
    user_id =    Column(String,        ForeignKey('user.user_id'))
    user = relationship(User, backref='photos')

我可以使用:

s.query(Photo).join(User.photo).all()

或者,如果我想要特定用户的所有照片:

s.query(Photo).join(User.photo).filter(User.user_id == '1234').all()

但是如何让它只返回 User.real_name 和大小?

【问题讨论】:

    标签: sql sqlalchemy


    【解决方案1】:

    .query() 中指定您想要返回的内容。第一个映射列指示要从中查询的基表。

    session.query(User.real_name, Photo.size).join(User.photos).all()
    

    这将为您提供每张照片的元组列表,例如 [('name', 12)]

    请简要考虑searching the documentation。它的作者非常彻底。

    【讨论】:

      猜你喜欢
      • 2011-06-28
      • 1970-01-01
      • 2021-05-06
      • 2014-02-22
      • 1970-01-01
      • 1970-01-01
      • 2011-10-22
      • 2010-12-10
      • 1970-01-01
      相关资源
      最近更新 更多