2011-11-29 35 views
8

鉴于以下模型,Django在第一次访问它们之后缓存相关对象吗?Django在访问后是否缓存相关的ForeignKey和ManyToManyField字段?

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的工作,但它的好,知道什么是在其他版本。

回答

5

在第一个示例the second query is cached中。 在第二种情况下(我相信),他们都将导致DB打,除非你在原来的查询中使用 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

前进进入一个一对多的关系被缓存在第一时间将相关对象进行访问。随后访问同一对象实例上的外键将被缓存。

请注意,select_related()QuerySet方法提前预先填充所有一对多关系的缓存。

+2

还是不太对。 ManyToMany查询根本没有被缓存 - 它们实际上等同于反向FK查找,所以不要缓存,除非在1.4中使用新的'prefetch_related'功能。 –

+0

谢谢。必要时我会自己处理ManyToMany字段上的缓存。 – bpscott

+0

答案需要修复并且更好,然后进行测试。在DJ1.5中我没有看到任何一种情况下的缓存。 – Bryce