gpt4 book ai didi

python - pony.orm 按关系中最新的实体排序

转载 作者:太空宇宙 更新时间:2023-11-03 16:20:37 24 4
gpt4 key购买 nike

假设我用 pony.orm 映射了这些表:

class Category(db.Entity):
threads = Set("Thread")

class Thread(db.Entity):
category = Required("Category")
posts = Set("Post")

class Post(db.Entity):
thread = Required("Thread")
timestamp = Required(datetime)

现在我想获取按最新帖子排序的特定类别的所有线程:

通过这一行,我获得了最新帖子的ID,但我想要该对象。

query = select((max(p.id), p.thread) for p in Post if p.thread.category.id == SOME_ID)
.order_by(lambda post_id, thread: -post_id)

当然我可以[(Post[i], thread) for i, thread in query]select(p for p in Post if p.id in [i for i ,_ 在查询中])

但这会创建额外的 sql 语句。所以我的问题是:如何使用单个 sql 语句获取某个类别中所有线程的最新帖子(按该帖子的时间戳排序)。

如果你不能使用 ORM,我就不会使用 db.execute(sql)

最佳答案

试试这个:

select((p, t) for t in Thread for p in t.posts
if p.id == max(p2.id for p2 in t.posts)
).order_by(lambda p, t: desc(p.id))

关于python - pony.orm 按关系中最新的实体排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38514429/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com