查询和选择 SQLAlchemy 中的特定列 [英] querying and selecting specific column in SQLAlchemy

查看:89
本文介绍了查询和选择 SQLAlchemy 中的特定列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How do I select specific columns from a query. For example, just the User name and size of a photo from:

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()

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

or maybe, if I want all the photos of a specfic user:

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

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

But how do I make it return just the User.real_name and the size?

推荐答案

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

Specify what you want returned in .query(). The first mapped column indicates the base table to query from.

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

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

This will get you a list of tuples like [('name', 12)] for every photo.

请考虑搜索文档.它的作者非常彻底.

Please consider searching the documentation briefly. It's author is very thorough.

这篇关于查询和选择 SQLAlchemy 中的特定列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆