Skip to content

Instantly share code, notes, and snippets.

@rtheunissen
Created November 30, 2015 21:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rtheunissen/b405b08abdcdb3f4f933 to your computer and use it in GitHub Desktop.
Save rtheunissen/b405b08abdcdb3f4f933 to your computer and use it in GitHub Desktop.
def prefetched_related(instance, name, default=None):
"""
Attempts to find and return prefetched data on a model.
Usage:
values, prefetched = prefetched_related(instance, 'name')
values : A list of prefetched values for the field.
prefetched : True if the requested field was prefetched on the instance.
"""
if hasattr(instance, '_prefetched_objects_cache'):
# Use the prefetched values only if the requested field was prefetched.
if name in instance._prefetched_objects_cache:
return instance._prefetched_objects_cache[name], True
return default, False
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment