Django 1.11 OuterRef生成无效的Postgres

时间:2017-05-26 21:19:21

标签: django postgresql

我有一个名为Brand的模型,其中包含一个名为" name"的字段,所以这样可行:

brands = (Brand
          .objects
          .annotate(as_string=models.functions.Concat('name',models.Value("''"))))

我有一个名为Item的模型,其中包含Brand的外键。以下不起作用:

annotated_brands = brands.filter(pk=models.OuterRef('brand'))
(Item
 .objects
 .annotate(brand_string=models.Subquery(annotated_brands.values('as_string'))))

具体来说,我得到了一个ProgrammingError:

missing FROM-clause entry for table "policeinventory_item"
LINE 1: ... FROM "PoliceInventory_brand" U0 WHERE U0."id" = (PoliceInve...

当我检查SQL查询时,这就诞生了。这是破碎的查询:

'SELECT "PoliceInventory_item"."id", "PoliceInventory_item"."_created", "PoliceInventory_item"."_created_by_id", "PoliceInventory_item"."_last_updated", "PoliceInventory_item"."_last_updated_by_id", "PoliceInventory_item"."brand_id", "PoliceInventory_item"."type", (SELECT CONCAT(U0."name", \'\') AS "as_string" FROM "PoliceInventory_brand" U0 WHERE U0."id" = (PoliceInventory_item."brand_id") ORDER BY U0."_created" DESC) AS "brand_string" FROM "PoliceInventory_item" ORDER BY "PoliceInventory_item"."_created" DESC'

注意嵌套id比较如何与PoliceInventory,NOT" PoliceInventory"因为它被引用到其他地方。以下查询按预期工作:

'SELECT "PoliceInventory_item"."id", "PoliceInventory_item"."_created", "PoliceInventory_item"."_created_by_id", "PoliceInventory_item"."_last_updated", "PoliceInventory_item"."_last_updated_by_id", "PoliceInventory_item"."brand_id", "PoliceInventory_item"."type", (SELECT CONCAT(U0."name", \'\') AS "as_string" FROM "PoliceInventory_brand" U0 WHERE U0."id" = ("PoliceInventory_item"."brand_id") ORDER BY U0."_created" DESC) AS "brand_string" FROM "PoliceInventory_item" ORDER BY "PoliceInventory_item"."_created" DESC'

问题似乎很明显是OuterRef错误地无法使用与外部查询相同的表引用,从而导致不匹配。有谁知道我如何说服OuterRef正确行事?

0 个答案:

没有答案