Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Django's RelatedManager not cache the object the lookup was called from, on the destination object?

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.

like image 340
Darb Avatar asked Nov 05 '22 06:11

Darb


1 Answers

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]
like image 83
mjtamlyn Avatar answered Nov 08 '22 00:11

mjtamlyn