Skip to content

Instantly share code, notes, and snippets.

@loic
Created October 4, 2013 05:53
Show Gist options
  • Save loic/6821530 to your computer and use it in GitHub Desktop.
Save loic/6821530 to your computer and use it in GitHub Desktop.
@classmethod
def prefetch_related(cls, instances):
pass
@classmethod
def prefetcher(cls, instances, queryset, fk_attr):
cache = {}
for instance in instances:
cache[getattr(instance, fk_attr + '_id')] = instance
for foreign in queryset.filter(pk__in=cache.keys()):
setattr(cache[foreign.pk], fk_attr, foreign)
@funkybob
Copy link

funkybob commented Oct 4, 2013

< loic84> Dog.prefetcher(dogs, Puppy.objects.filter(cute=True), 'parent')
< loic84> well there are 3 arguments, the first one is your instances that are already fetched.
< loic84> for example dogs = Dog.objects.filter(age__gt=2)
< loic84> then the QS is whatever you want to "prefetch".
< loic84> and the third argument is the name of the attribute (FK attname basically) that will be used to attach the prefetched item to the parent item.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment