此查询集包含对外部查询的引用,并且只能在子查询中使用



型号ProductFilter具有productsManyToManyField。我需要从最高优先级的product.filters(ProductFilter.priority字段(中获取属性to_export

我发现了这个

filters = ProductFilter.objects.filter(
products__in=[OuterRef('pk')]
).order_by('priority')
Product.objects.annotate(
filter_to_export=Subquery(filters.values('to_export')[:1])
)

但它提高了

ValueError:此查询集包含对外部查询的引用,只能在子查询中使用。

你知道为什么吗?

这是旧的,但无论如何:

看起来相关查找无法在此处处理OuterRefproducts__in=[OuterRef('pk')]

注意:在Django 3.2中,OP的例子产生了不同的错误,即TypeError: Field 'id' expected a number but got ResolvedOuterRef(pk).

由于这里只有一个pk值,我认为您不需要使用__in查找。

以下似乎有效,尽管我不确定这是否正是OP想要的:

filters = ProductFilter.objects.filter(
products=OuterRef('pk')  # replaced products__in lookup
).order_by('priority')
products = Product.objects.annotate(
filter_to_export=Subquery(filters.values('to_export')[:1])
)

生成的SQL(稍微简化了表名(:

SELECT "product"."id", (
SELECT U0."to_export" 
FROM "productfilter" U0 
INNER JOIN "productfilter_products" U1 
ON (U0."id" = U1."productfilter_id") 
WHERE U1."product_id" = "product"."id" 
ORDER BY U0."priority" DESC LIMIT 1
) AS "filter_to_export" 
FROM "product"

最新更新