The Prefetch
is being executed as a 2nd query after the products query, thus its not possible to filter out products based on the prefetch. You need to repeat the prefetch filtration as either Subquery or inside the Count which you are trying to make.
In order for the Count to work try the following:
filtered_qs = Product.objects.annotate(
offers_count=Count('offers', filter=Q(offers__price__gt=1000))
).filter(
offers_count__gt=0
).prefetch_related(
prefetch
)
In order to do it with a Subquery you need something like this:
filtered_qs = Product.objects.annotate(
offers_count=Subquery(
prefetch_qs.filter(product=OuterRef('pk'))
.values('product')
.annotate(count=Count('pk'))
.values('count')
)
).filter(
offers_count__gt=0
).prefetch_related(
prefetch
)
The Subquery approach may look a little bit hard to understand why its done this way, I've tried to explain it in some old question here