Created
August 17, 2017 21:05
-
-
Save LucasMagnum/21074818968d99d7507d24526fa63818 to your computer and use it in GitHub Desktop.
Prefetch using queryset #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 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