给定以下模型,Django在第一次访问相关对象后是否会对其进行缓存?
class Post(models.Model):
authors = models.ManyToManyField(User)
category = models.ForeignKey(Category)
例如:
post = Post.objects.get(id=1)
# as i understand this hits the database
authors1 = post.authors.all()
# does this his the database again?
authors2 = post.authors.all()
# as i understand this hits the database
category1 = post.category
# does this hit the database again?
category2 = post.category
注意:当前正在使用Django 1.3,但最好了解其他版本中的可用功能。
最佳答案
在第一个示例the second query is cached。在第二种情况下(我相信),除非您在原始查询上使用select_related
,否则它们都将导致数据库命中:
post = Post.objects.select_related('category').get(id=1)
编辑
对于第二个示例,我错了。如果您在原始查询中使用
select_related
,则完全不会再次访问该数据库(ForeignKey将立即缓存)。如果不使用select_related
,则将在第一个查询上命中数据库,但第二个查询将被缓存。从:
https://docs.djangoproject.com/en/dev/topics/db/queries/#one-to-many-relationships