Python Django queryset的对象属性正在命中数据库
我在Django中有一个模型,它有一个命中数据库的属性:Python Django queryset的对象属性正在命中数据库,python,django,Python,Django,我在Django中有一个模型,它有一个命中数据库的属性: class Post(models.Model): 已创建\u at=models.DateTimeField(自动\u now\u add=True) 更新的\u at=models.DateTimeField(自动\u now=True) 类注释(models.Model): 已创建\u at=models.DateTimeField(自动\u now\u add=True) 更新的\u at=models.DateTimeField
class Post(models.Model):
已创建\u at=models.DateTimeField(自动\u now\u add=True)
更新的\u at=models.DateTimeField(自动\u now=True)
类注释(models.Model):
已创建\u at=models.DateTimeField(自动\u now\u add=True)
更新的\u at=models.DateTimeField(自动\u now=True)
comment=models.CharField()
post=模型.外键(post,相关的\u name='comments')
@财产
def上一条注释(自我):
尝试:
返回self.post.comments.filter(created_at_ult=self.created_at).order_by('-created_at')[0]
除索引器外:
一无所获
但是,当我使用comment.objects.all()
获取所有注释对象时,很明显,每次查询集中包含每个对象时,它都会访问数据库以查找以前的注释
我觉得我这样做是非常错误的。如何在queryset内的每个对象中包含previous_comment属性,而不必多次访问数据库?看起来您想玩一下。我想你需要做的是打电话:
Comment.objects.prefetch_related('post_comments').all()
这将为您提供一个更大的查询,其中包含一些连接,而不是许多较小的查询。我花了一段时间来尝试这些方法,所以我建议你也这样做,以获得正确的平衡。你可以像一个双键链表一样构建,外键是
next
和prev