[Django]-Using prefetch_related to get only a particular entry of a relation

10👍

Is it necessary to do the query on the A objects rather than the B objects? If you reverse what you do the additional lookup on, you could use select_related():

foo = B.objects.select_related('aa').get(i=2)

This has the advantage of reducing your number of database hits. Because prefetch_related() always does its own database lookup, your proposed scenario of using prefetch_related() isn’t any more efficient, as written, than simply doing:

a = A.objects.get(pk=1)
b = a.fka.get(i=2)

That’s not to say it wouldn’t be more efficient in scenarios with more complex filtering, but select_related() uses a SQL join and therefore only hits the database once. That said, if you absolutely must lookup the A objects first, the best answer would be: upgrade to Django 1.7. The new Prefetch command in Django 1.7 allows for more complex operations on prefetch_related(), including filtering, by allowing you to specify custom querysets:

qs = B.objects.filter(i=2)
foo = A.objects.get(pk = 1).prefetch_related(Prefetch('fka',qs))

Leave a comment