Django一旦被访问就会缓存相关的ForeignKey和ManyToManyField字段吗?

bps*_*ott 10 python django django-models

鉴于以下模型,Django是否在第一次访问后缓存相关对象?

class Post(models.Model):
    authors = models.ManyToManyField(User)
    category = models.ForeignKey(Category)
Run Code Online (Sandbox Code Playgroud)

例如:

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
Run Code Online (Sandbox Code Playgroud)

注意:目前正在使用Django 1.3,但很高兴知道其他版本中可用的内容.

Tim*_*ony 6

在第一个示例中,缓存第二个查询.在第二种情况下(我相信),除非您select_related在原始查询上使用,否则它们都会导致数据库命中:

post = Post.objects.select_related('category').get(id=1)
Run Code Online (Sandbox Code Playgroud)

编辑

我错了第二个例子.如果select_related在原始查询中使用,则不会再次访问数据库(ForeignKey会立即缓存).如果您不使用select_related,您将在第一个查询中点击数据库,但第二个查询将被缓存.

从:

https://docs.djangoproject.com/en/dev/topics/db/queries/#one-to-many-relationships

第一次访问相关对象时,将缓存对一对多关系的转发访问.对高速缓存在同一对象实例上的外键的后续访问.

请注意,select_related()QuerySet方法以递归方式预先填充所有一对多关系的缓存.

  • 还是不太对劲.ManyToMany查询根本没有缓存 - 它们实际上只相当于反向FK查找,因此除非在1.4中使用新的`prefetch_related`功能,否则不要缓存. (2认同)