Discovering a relation should cache the originator if applicable
|Reported by:||Owned by:||Aymeric Augustin|
|Component:||Database layer (models, ORM)||Version:||master|
|Severity:||Normal||Keywords:||related, cache, ForeignKey, OneToOneField, prefetch_related|
|Cc:||Triage Stage:||Ready for checkin|
|Has patch:||yes||Needs documentation:||no|
|Needs tests:||no||Patch needs improvement:||no|
Currently, related fields will not cache the originator object (which holds the field) into the returned objects. This patch makes reverse ForeignKey and OneToOneField relations cache the originator(s) into the queryset, and then in turn to the returned objects.
In example, it validates this test, with Pool objects having a ForeignKey to Tournament objects:
def test_fk(self): with self.assertNumQueries(2): tournament = Tournament.objects.get(pk=1) pool = tournament.pool_set.all() self.assertIs(tournament, pool.tournament)
Without this patch, the expression
pool.tournament would trigger a third query and create a different instance. It also works with .prefetch_related() calls.