简体   繁体   中英

Django query corresponding to a raw query

I am executing the following raw query and getting error: 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)

Can someone correct this query or help me with the corresponding query for django?

Using .raw() only works if you are returning things which can be mapped to model instances. However, since you are returning aggregations, these can't be mapped to Revenue objects, which is why you are getting errors with your code.

What you need to do is execute your custom SQL directly against the database , along the lines of:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM