如何将Django ORM查询转换为SQL行查询?

时间:2019-07-16 19:04:08

标签: python sql django

我有Django ORM查询:

month = InfraVltgDetail.objects.annotate(
        month=TruncMonth('create_dt'))
        .values('month').annotate(
        name_count=Count('id'))
        .values('month', 'name_count')

我正在使用month.query转换SQL行查询。

#print(by_month.query)

output:

SELECT django_datetime_trunc('month', "portal_infravltgdetail"."create_dt", 'UTC')
 AS "month", COUNT("portal_infravltgdetail"."id") 
AS "name_count" FROM "portal_infravltgdetail" 
GROUP BY django_datetime_trunc('month', "portal_infravltgdetail"."create_dt", 'UTC')

当我使用输出SQL行查询执行但出现错误时。

我如何运行SQL行查询:

import psycopg2

conn = psycopg2.connect(database="test",
        user = "postgres",
        password = "postgres",
        host = "localhost",
        port = "5432")
cur = conn.cursor()
cur.execute(output_query)
cur.fetchall()

能否请您帮我将Django ORM转换为sql。

0 个答案:

没有答案