访问它们后,Django是否会缓存相关的ForeignKey和ManyToManyField字段? [英] Does Django cache related ForeignKey and ManyToManyField fields once they're accessed?
问题描述
给出以下模型,Django是否在第一次访问相关对象后缓存它们?
Given the following model, does Django cache the related objects after the first time they're accessed?
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,但最好知道其他版本中的可用内容。
Note: currently working with Django 1.3, but it's good to know what's available in other versions.
推荐答案
在第一个示例中,第二个查询已被缓存。 在第二种情况下(我相信),除非您在原始查询上使用 select_related
,否则它们都将导致数据库命中:
In the first example the second query is cached. In the second case (I believe) they will both cause a DB hit unless you use select_related
on the original query:
post = Post.objects.select_related('category').get(id=1)
编辑
我对第二个例子是错误的。如果您在原始查询中使用 select_related
,您将完全不会再访问该数据库(ForeignKey将立即缓存)。如果您不使用 select_related
,则将在第一个查询中命中数据库,但第二个查询将被缓存。
I'm wrong about the second example. If you use select_related
in the original query, you won't hit the database at all again (The ForeignKey is cached immediately). If you don't use select_related
, you will hit the DB on the first query but the second query will be cached.
发件人:
https://docs.djangoproject.com/en/dev/topics/db/queries/#one-to-many-relationships
第一次访问相关对象时,将缓存对多对多关系的前向访问。
Forward access to one-to-many relationships is cached the first time the related object is accessed. Subsequent accesses to the foreign key on the same object instance are cached.
请注意,select_related()QuerySet方法以递归方式预先填充了所有前面一对多关系的缓存。时间。
Note that the select_related() QuerySet method recursively prepopulates the cache of all one-to-many relationships ahead of time.
这篇关于访问它们后,Django是否会缓存相关的ForeignKey和ManyToManyField字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!