Skip to content

Instantly share code, notes, and snippets.

@LucasMagnum
Created August 17, 2017 21:05
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/21074818968d99d7507d24526fa63818 to your computer and use it in GitHub Desktop.
Save LucasMagnum/21074818968d99d7507d24526fa63818 to your computer and use it in GitHub Desktop.
Prefetch using queryset #djangotip02
# $ python app/manage.py shell
from django.db.models import Prefetch
from .models import Category
def categories_list_active_subcategories_using_prefetch_queryset():
categories_qs = Category.objects.prefetch_related(
Prefetch(
'subcategories',
queryset=Category.objects.filter(is_active=True),
)
)
categories = []
for category in categories_qs:
subcategories = [sub.name for sub in category.subcategories.all()]
categories.append({
'name': category.name,
'is_active': category.is_active,
'subcategories': subcategories
})
return categories
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment