如何排除具有空 prefetch_lated 字段的行

Kon*_*rov 2 python django django-orm

prefetch_related用过Prefetch

prefetch_qs = Offer.objects.filter(price__gt=1000)
prefetch = Prefetch('offers', queryset=prefetch_qs)
Run Code Online (Sandbox Code Playgroud)

如何排除包含空报价的行?它不起作用,因为注释计算了所有报价(未在 中过滤prefetch):

filtered_qs = Product.objects.annotate(
    offers_count=Count('offers')
).filter(
    offers_count__gt=0
).prefetch_related(
    prefetch      
)
Run Code Online (Sandbox Code Playgroud)

Tod*_*dor 5

Prefetch是在产品查询之后作为第二个查询执行的,因此不可能根据预取过滤掉产品。您需要将预取过滤作为子查询或您尝试进行的计数内重复。

为了使计数正常工作,请尝试以下操作:

filtered_qs = Product.objects.annotate(
    offers_count=Count('offers', filter=Q(offers__price__gt=1000))
).filter(
    offers_count__gt=0
).prefetch_related(
    prefetch
)
Run Code Online (Sandbox Code Playgroud)

为了使用子查询来做到这一点,你需要这样的东西:

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
)
Run Code Online (Sandbox Code Playgroud)

子查询方法可能看起来有点难以理解为什么这样做,我试图在一些老问题中解释