我想为每个帖子显示 5 个最新评论的帖子列表。如何使用最少数量的数据库查询来做到这一点?
Post.objects.filter(...).prefetch_related('comment_set')
检索所有评论,而我只需要其中的几个。
我会去两个查询。首先获取帖子:
posts = list(Post.objects.filter(...))
现在运行原始 SQL 查询UNION
(注意:为简单起见省略了排序):
sql = "SELECT * FROM comments WHERE post_id=%s LIMIT 5"
query = []
for post in posts:
query.append( sql % post.id )
query = " UNION ".join(query)
并运行它:
comments = Comments.objects.raw(query)
之后,您可以循环评论并在 Python 端对它们进行分组。
我没试过,但看起来还可以。
对于您的问题,还有其他可能的解决方案(可能只需要一个查询),看看这个:
http://www.xaprb.com/blog/2006/12/07/how-to-select-the-firstleastmax-row-per-group-in-sql/