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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With