Skip to content

Instantly share code, notes, and snippets.

@LucasMagnum
Created August 17, 2017 20:56
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 LucasMagnum/a13afb6ad657136d7c17f5e53d2a6f68 to your computer and use it in GitHub Desktop.
Save LucasMagnum/a13afb6ad657136d7c17f5e53d2a6f68 to your computer and use it in GitHub Desktop.
Prefetch with to attr #djangotip02
# $ python app/manage.py shell
from products.models import Category
from django.db.models import Prefetch
# Get the first category with subcategories
category = Category.objects.filter(subcategories__isnull=False).first()
# Try to access the `active_subcategories` attribute
category.active_subcategories
# Now let’s load our object with the new Prefetch
category = Category.objects.filter(
subcategories__isnull=False
).prefetch_related(
  Prefetch(
'subcategories',
queryset=Category.objects.filter(is_active=True),
to_attr='active_subcategories'
)).first()
# Try to access the `active_subcategories` attribute
category.active_subcategories
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment