Created
August 17, 2017 20:56
-
-
Save LucasMagnum/a13afb6ad657136d7c17f5e53d2a6f68 to your computer and use it in GitHub Desktop.
Prefetch with to attr #djangotip02
This file contains 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
# $ 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