Created
October 4, 2013 05:53
-
-
Save loic/6821530 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
< 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.