我正在尝试选择最新回复时间顺序下降的最新线程(Thread)(回复是Post模型,这是标准的论坛查询)。在SQL中我会这样写:
SELECT * FROM thread AS t ORDER BY (SELECT MAX(posted_at) FROM post WHERE thread_id = t.id) DESC
我如何在SQLAlchemy中执行此类操作?我试过这样的事情:
scalar = db.select[func.max(Post.posted_at)].where(Post.thread_id == Thread.id).as_scalar()
threads = Thread.query.order_by(scalar.desc()).all()
但似乎我不明白标量是如何工作的。第五次阅读文档无济于事。有人可以帮我在SQLAlchemy中编写这样的查询吗?我在这个应用程序中使用flask-sqlalchemy和MySQL。
答案 0 :(得分:3)
对我来说很好,这是一个测试:
from sqlalchemy import *
from sqlalchemy.orm import *
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class Thread(Base):
__tablename__ = 'thread'
id = Column(Integer, primary_key=True)
class Post(Base):
__tablename__ = 'post'
id = Column(Integer, primary_key=True)
thread_id = Column(Integer, ForeignKey('thread.id'))
posted_at = Column(String)
s = Session()
scalar = select([func.max(Post.posted_at)]).where(Post.thread_id == Thread.id).as_scalar()
q = s.query(Thread).order_by(scalar.desc())
print q
输出(注意我们只是在这里打印SQL):
SELECT thread.id AS thread_id
FROM thread ORDER BY (SELECT max(post.posted_at) AS max_1
FROM post
WHERE post.thread_id = thread.id) DESC
看起来非常像您的查询