我正在执行以下原始查询并收到错误:Raw query must include the primary key
。
user = User.objects.get(email_id=request.session['email_id'])
query = 'select date, sum(revenue) from dashboard_revenue where app_id_id IN (select id from dashboard_app where user_id_id=1) group by date'
details = Revenue.objects.raw(query)
context = {'details': details}
return render(request, 'index.html', context)
有人可以更正此查询或帮助我查找django的相应查询吗?
答案 0 :(得分:3)
只有在返回可以映射到模型实例的内容时,才使用.raw()
。但是,由于您要返回聚合,因此无法将这些聚合映射到Revenue
个对象,这就是您的代码出错的原因。
您需要做的是execute your custom SQL directly against the database,其中包括:
from django.db import connection
def my_custom_sql(self):
cursor = connection.cursor()
query = 'select date, sum(revenue) from dashboard_revenue where app_id_id IN (select id from dashboard_app where user_id_id=%s) group by date'
user_id = 1
cursor.execute(query, [user_id])
rows = cursor.fetchall()
return rows