给定两个模型:
class Post(models.Model):
...
class Comment(models.Model):
post = models.ForeignKey(Post)
...
有没有一种好方法可以获取一组帖子的最后 3 条评论(即在一次往返数据库中而不是每个帖子一次)?一个天真的实现来说明我的意思:
for post in Post.objects.filter(id__in=some_post_ids):
post.latest_comments = list(Comment.objects.filter(post=post).order_by('-id')[:3])
给定some_post_ids == [1, 2]
,以上将导致3个查询:
[{'sql': 'SELECT "myapp_post"."id" FROM "myapp_post" WHERE "myapp_post"."id" IN (1, 2)', 'time': '0.001'},
{'sql': 'SELECT "myapp_comment"."id", "myapp_comment"."post_id" FROM "myapp_comment" WHERE "myapp_comment"."post_id" = 1 LIMIT 3', 'time': '0.001'},
{'sql': 'SELECT "myapp_comment"."id", "myapp_comment"."post_id" FROM "myapp_comment" WHERE "myapp_comment"."post_id" = 2 LIMIT 3', 'time': '0.001'}]