Why doesn't Django RelatedManager cache the object from which the search was called on the target?

If I have the following models:

class Fubar(models.Model): name = models.CharField() class Related(models.Model): fubar = models.ForeignKey(Fubar) 

I would expect ORM to magically cache the parent Fubar if I accessed Related to .related_set:

 fubar = Fubar.objects.all()[0] related = fubar.related_set.all()[0] related.fubar 

This leads to 3 queries, where I expect it to lead to only 2, since related.fubar can be optimized in this context to be the same object that I called the LinkedManager.

+4
source share
2 answers

As long as I'm not sure why this is not working (other than perhaps a magic reduction), you can easily avoid the extra request with

 fubar.related_set.select_related('fubar')[0] 
+2
source

In django 1.4, they introduce prefetch_related , which automatically retrieves related objects in one package for each of the specified searches.

0
source

Source: https://habr.com/ru/post/1393937/


All Articles