To get max value from a simple table of values, I can write the following query in Django:
MyTable.objects.aggregate(Max(\'value\'))
The SQ
U can use
ModelName.objects.raw('SELECT 1 as id , max(value) FROM mytable')
You should use custom SQL instead of Manager.raw()
method:
from django.db import connection
cursor = connection.cursor()
cursor.execute('SELECT max(value) FROM mytable')
max_value = cursor.fetchone()[0]
I would do something like:
select id, value from mytable order by value desc limit 1
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?
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'))