How to prefetch a queryset that uses distinct?

Hmm… I think this error is happening because the Subquery approach returns multiple rows. So you could try to:

  1. Create a subquery to check if there are products with the same product type and the tag.
  2. Use Prefetch to prefetch the filtered tags for each feature.
  3. Prefetch the features with the filtered tags for each product type.

Here’s the updated code:

from django.db.models import OuterRef, Subquery, Exists, Prefetch, Q

# Subquery to check if there are products with the same product type and the tag
tags_with_same_product_type = Tag.objects.filter(
    feature=OuterRef('pk'),
    products__product_type=OuterRef(OuterRef('product_type'))
)

# Use Exists to filter tags
filtered_tags = Tag.objects.filter(
    Exists(tags_with_same_product_type)
)

# Prefetch the filtered tags for each feature
features_with_filtered_tags = Feature.objects.prefetch_related(
    Prefetch('tags', queryset=filtered_tags, to_attr='filtered_tags')
)

# Prefetch the features with the filtered tags for each product type
product_types_with_features_and_filtered_tags = ProductType.objects.prefetch_related(
    Prefetch('features', queryset=features_with_filtered_tags)
).all()

# Now you can iterate over the product types and access the filtered tags for each feature
for product_type in product_types_with_features_and_filtered_tags:
    print(f'Product Type: {product_type.name}')
    for feature in product_type.features.all():
        print(f'  Feature: {feature.name}')
        for tag in feature.filtered_tags:
            print(f'    Tag: {tag.name}')