[Django]-Django avoid extra queries using prefetch_related not working

8👍

When you call filter(), this creates a different queryset, so Django can’t use the data from prefetch_related.

You can move the filter into the queryset for the Prefetch object.

qs = User.objects.all().prefetch_related(
    Prefetch('userextrainfo_set', queryset=UserExtraInfo.objects.filter(
        info_item__type=general_data_type
    ).select_related('info_item'), to_attr='general_userextrainfo')
)

then don’t use filter() when accessing the related items in the queryset.

for user in qs:
    user.general_userextrainfo.values_list('info_item__title', flat=True))

Leave a comment