6

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.

Darb
  • 1,463
  • 11
  • 10
  • 1
    This is fixed in django 1.5 - https://docs.djangoproject.com/en/dev/releases/1.5-beta-1/#caching-of-related-model-instances – Darb Nov 29 '12 at 20:00

2 Answers2

2

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]
mjtamlyn
  • 1,704
  • 13
  • 8
  • That does help, thanks. I was hoping it would be fubar's exact object/state, since in the current instance I am fetching and caching other information on the fubar object. I will just have to maintain my own cache of objects and lookup using the fubar_id. – Darb Jan 31 '12 at 10:43
0

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.

Ross
  • 17,861
  • 2
  • 55
  • 73