Ankit Jaiswal
Ankit Jaiswal

Reputation: 23427

Django 1.0 fetching max value from database

How can I execute max query in django 1.0 version. I tried from django.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

Upvotes: 0

Views: 216

Answers (1)

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]

Upvotes: 1

Related Questions