Django 1.0 fetching max value from database
How can I execute max query in django 1.0 version. I tried from d开发者_如何学Gojango.db.models import Max but seems that its available only in 1.1 version and gives error with 1.0.
Please suggest.
Thanks in advance
First of all, it would be from django.db.models import Max
, but you're right it was introduced in 1.1
and would throw an ImportError anyways.
You could potentially use extra()
http://docs.djangoproject.com/en/1.0/ref/models/querysets/#extra-select-none-where-none-params-none-tables-none-order-by-none-select-params-none
Model.objects.extra(select={'max':'MAX(myfield)'})[0].max
Or go to SQL:
http://docs.djangoproject.com/en/dev/topics/db/sql/#executing-custom-sql-directly
from django.db import connection
cursor = connection.cursor()
cursor.execute("SELECT MAX(myfield) from myapp_mytable")
max = cursor.fetchone()[0]
精彩评论