Python 与原始查询相对应的Django查询
我正在执行以下原始查询并出现错误:Python 与原始查询相对应的Django查询,python,django,Python,Django,我正在执行以下原始查询并出现错误:原始查询必须包含主键 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.
原始查询必须包含主键
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的相应查询?使用.raw()
仅当您返回可以映射到模型实例的内容时才有效。但是,由于您返回的是聚合,因此这些聚合无法映射到Revenue
对象,这就是代码出错的原因
您需要做的是,大致如下:
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
使用.raw()
仅在返回可以映射到模型实例的内容时有效。但是,由于您返回的是聚合,因此这些聚合无法映射到Revenue
对象,这就是代码出错的原因
您需要做的是,大致如下:
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
使用.raw()
仅在返回可以映射到模型实例的内容时有效。但是,由于您返回的是聚合,因此这些聚合无法映射到Revenue
对象,这就是代码出错的原因
您需要做的是,大致如下:
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
使用.raw()
仅在返回可以映射到模型实例的内容时有效。但是,由于您返回的是聚合,因此这些聚合无法映射到Revenue
对象,这就是代码出错的原因
您需要做的是,大致如下:
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
类似于:是否仅使用原始sql?或者使用queryset也可以?@levi对queryset的使用表示赞赏:)类似于:是否只使用原始sql?或者使用queryset也可以?@levi对queryset的使用表示赞赏:)类似于:是否只使用原始sql?或者使用queryset也可以?@levi对queryset的使用表示赞赏:)类似于:是否只使用原始sql?或者使用queryset也很好?@levi使用queryset很受欢迎:)