Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

sql - querying and selecting specific column in 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')

I can use:

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...