# How to prefetch a queryset that uses distinct?

**URL:** <https://forum.djangoproject.com/t/how-to-prefetch-a-queryset-that-uses-distinct/33186>\
**Category:** Using the ORM\
**Created:** [July 22, 2024, 11:27am UTC](https://forum.djangoproject.com/t/how-to-prefetch-a-queryset-that-uses-distinct/33186 "2024-07-22T11:27:42Z")\
**Posts on this page:** 1\
**Page:** 2

<div class="post-metadata">

**Author:** ![anefta](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/anefta/32/10649_2.png) [@anefta](https://forum.djangoproject.com/u/anefta)\
**Post date:** [August 2, 2024, 12:57pm UTC](https://forum.djangoproject.com/t/how-to-prefetch-a-queryset-that-uses-distinct/33186/21 "2024-08-02T12:57:18Z")

</div>

> [@PierreMDL](#):
>
> My understanding is that an an

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:

```auto
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}')

```

[Previous page](https://forum.djangoproject.com/t/how-to-prefetch-a-queryset-that-uses-distinct/33186.md?page=1)
