If I have the following models:

class Fubar(models.Model):
    name = models.CharField()

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

I would expect that the ORM would magically cache the parent Fubar object if I accessed Related using .related_set:

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

That results in 3 queries, where I would expect it to only result in 2, since related.fubar could be optimised in this context to be the same object I called a RelatedManager on.

2

There are 2 answers

1
mjtamlyn On

Whilst I'm not sure why this doesn't work (except maybe magic reduction), you could easily avoid the extra query with

fubar.related_set.select_related('fubar')[0]
0
Ross On

In django 1.4 they are introducing prefetch_related which will automatically retrieve, in a single batch, related objects for each of the specified lookups.