On 9/2/15 11:05 PM, Ryan Eberhardt wrote:
Hello,
I have User and Session classes like this:
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
sessions = relationship('Session')
@property
def last_login_time(self):
return sorted(self.sessions, reverse=True, key=lambda x:
x.time)[0]
...
class Session(Base):
__tablename__ = 'sessions'
id = Column(Integer, primary_key=True)
user_id = Column(Integer, ForeignKey('users.id'))
time = Column(DateTime)
...
The last_login_time property sorts the user's sessions by date and
returns the most recent one. Now I want to query users using this
property. I know I can use hybrid properties to do this, but I have no
idea how to write the sql expression with sqlalchemy (i.e. I don't
know how to get a user's most recent session using sqlalchemy
expressions). Any ideas on how to do this?
when you want to sort by a related table in SQL you typically need to
have a JOIN that is built externally to the attribute itself. A less
efficient way is perhaps to use a correlated subquery and order by that,
but that would be the only way to keep it self-contained:
@last_login_time.expression
def last_login_time(cls):
return select([max(Session.time)]).where(Session.user_id ==
cls.id).correlate(User).as_scalar()
Thank you!
--
You received this message because you are subscribed to the Google
Groups "sqlalchemy" group.
To unsubscribe from this group and stop receiving emails from it, send
an email to [email protected]
<mailto:[email protected]>.
To post to this group, send email to [email protected]
<mailto:[email protected]>.
Visit this group at http://groups.google.com/group/sqlalchemy.
For more options, visit https://groups.google.com/d/optout.
--
You received this message because you are subscribed to the Google Groups
"sqlalchemy" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To post to this group, send email to [email protected].
Visit this group at http://groups.google.com/group/sqlalchemy.
For more options, visit https://groups.google.com/d/optout.