0

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?

Piyush aggarwal
  • 750
  • 2
  • 14
  • 25

1 Answers1

3

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