Django子查询,ORA-00904:无效的标识符

时间:2019-01-28 18:50:42

标签: python sql django oracle django-models

下面的查询作为原始sql

SELECT WORK_ORDER.*,(SELECT COMPLETE FROM SAMPLE WHERE COMPLETE = 'TRUE' AND
ARF_ID = WORK_ORDER.ARF_ID AND ROWNUM <= 1) AS SAMPLE_COMPLETE, (DUE_DATE - 
SYSDATE) AS DUE_IN FROM WORK_ORDER WHERE COMPLETE = 'FALSE' ORDER BY 
DUE_DATE ASC  

以下Django查询集不起作用

subquery = Sample.objects.filter(complete = 'TRUE', arf_id = models.OuterRef('arf_id'))[:1]
workOrderList = WorkOrder.objects.annotate(sample_complete= models.Subquery(subquery.values('complete'))).annotate(due_in= models.F('due_date') - datetime.now()).filter(complete = 'FALSE').order_by('due_date')   

在运行workOrderList.query时会生成此查询

SELECT "WORK_ORDER"."ARF_ID", "WORK_ORDER"."COMPANY_NAME", 
"WORK_ORDER"."COMPANY_ADDRESS", "WORK_ORDER"."CONTACT_TELEPHONE", 
"WORK_ORDER"."ORDER_DATE", "WORK_ORDER"."DUE_DATE", 
"WORK_ORDER"."ARF_NUMBER", "WORK_ORDER"."COMPLETE", 
"WORK_ORDER"."COMPLETE_DATE", "WORK_ORDER"."REPORTED", 
"WORK_ORDER"."REPORTED_DATE", "WORK_ORDER"."COMPANY_CODE", (SELECT * FROM 
(SELECT "_SUB".* FROM (SELECT U0."COMPLETE" AS Col1 FROM "SAMPLE" U0 WHERE 
(U0."COMPLETE" = TRUE AND U0."ARF_ID" = ("WORK_ORDER"."ARF_ID"))) "_SUB" 
WHERE ROWNUM <= 1)) AS "SAMPLE_COMPLETE", ("WORK_ORDER"."DUE_DATE" - 2019- 
01-28 13:00:51.043013) AS "DUE_IN" FROM "WORK_ORDER" WHERE 
"WORK_ORDER"."COMPLETE" = FALSE ORDER BY "WORK_ORDER"."DUE_DATE" ASC

这将返回错误
cx_Oracle.DatabaseError: ORA-00904: "WORK_ORDER"."ARF_ID": invalid identifier

我使用的是Django 1.11.13,这是一个旧数据库,我很乐意使用原始sql查询数据,但想以正确的方式学习/使用Django ORM,因此请修复或解释为何此方法无效对我有帮助。

1 个答案:

答案 0 :(得分:0)

在这种情况下,使用Exists()子类是实现整体目标的解决方案:

workOrderList = WorkOrder.objects.annotate(sample_complete= models.Exists(subquery.values('complete')))
.annotate(due_in= models.F('due_date') - datetime.now()).filter(complete = 'FALSE').order_by('due_date')

我仍在寻找使用Subquery()方法的解决方案