Primary key requirement in raw SQL complicates the query in Django Primary key requirement in raw SQL complicates the query in Django postgresql postgresql

Primary key requirement in raw SQL complicates the query in Django


You should use custom SQL instead of Manager.raw() method:

from django.db import connectioncursor = connection.cursor()cursor.execute('SELECT max(value) FROM mytable')max_value = cursor.fetchone()[0]


U can use

ModelName.objects.raw('SELECT 1 as id , max(value) FROM mytable')


I just had same issue, @Tinashe Robert's not working for me. May I share my solution(Python 3.7.7, Django 3.0.5):

PS: Yes, @catavaran's answer is native Python, but if one really want to use RAW?

  • Firstly, primary_key needs to be appointed to one column in MySQL DB field, i.e.:
 class MyTable(model.Model):     id = models.AutoField(primary_key=True)     value = models.IntegerField(10)     ... 

with API shell:

>>> MyTable.objects.raw('SELECT id, max(value) as mx from MyTable')[0].mx

or simpler solution:

>>> from django.db.models import Max>>> MyTable.objects.all().aggregate(Max('value'))