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.
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With