簡體   English   中英

訪問它們后,Django是否會緩存相關的ForeignKey和ManyToManyField字段?

[英]Does Django cache related ForeignKey and ManyToManyField fields once they're accessed?

給定以下模型,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,但最好了解其他版本中的可用功能。

在第一個示例中,第二個查詢被緩存 在第二種情況下(我相信),除非您在原始查詢上使用 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方法會提前遞歸地預先填充所有一對多關系的緩存。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM