[Django]-Django get the max PK

5👍

You can use aggregation to get the Max value. For example, if you wanted the max ID of your Users table:

from django.contrib.auth.models import User
from django.db.models import Max

users = User.objects.all()
max = users.aggregate(Max('id'))

This would give you {'id__max': 10} or whatever the greatest ID is.

2👍

This is a bit old, but I came across this same problem and it can be achieved using latest. something like

try:
    return some_table_model.ojects.latest('pk').pk
except some_table_model.DoesNotExist:
    return 0

this is of course assuming that your pk’s are numeric and not composite. Otherwise you could use id or some other field as suggested above

2👍

easy. you only need to get pk of the latest object:

YourModel.ojects.latest('pk').pk

0👍

You can use this

YourModel.objects.all().order_by(-id).first().id

0👍

Here are four different ways to get the max PK, along with the accompanying SQL queries on an OpenMRS database on MySQL 8 (it’s what I had available). Only the aggregation uses MAX():

from django.db import connection
from django.db.models import Max

c0 = Concept.objects.all().order_by('-concept_id').values_list('concept_id')[0]
# this is just the last object in the queryset
# this will *mostly* give you the highest PK, but rather not rely on it
c1 = Concept.objects.last().concept_id
# get the latest object by concept_id
c2 = Concept.objects.latest('concept_id').concept_id
# use aggregation, this is the only one of these methods that uses MAX()
c3 = Concept.objects.all().aggregate(Max('concept_id'))

# show the last 4 SQL queries
connection.queries[-4:]

connection.queries is a list of dicts with sql and times, so we massage it a bit with

print("\n".join([q['sql'].replace("`", "") for q in connection.queries[-4:]]))

to get the following four corresponding SQL queries:

SELECT concept.concept_id FROM concept ORDER BY concept.concept_id DESC LIMIT 1
SELECT concept.concept_id, concept.retired, concept.short_name, concept.description, concept.form_text, concept.datatype_id, concept.class_id, concept.is_set, concept.creator, concept.date_created, concept.version, concept.changed_by, concept.date_changed, concept.retired_by, concept.date_retired, concept.retire_reason, concept.uuid FROM concept ORDER BY concept.concept_id DESC LIMIT 1
SELECT concept.concept_id, concept.retired, concept.short_name, concept.description, concept.form_text, concept.datatype_id, concept.class_id, concept.is_set, concept.creator, concept.date_created, concept.version, concept.changed_by, concept.date_changed, concept.retired_by, concept.date_retired, concept.retire_reason, concept.uuid FROM concept ORDER BY concept.concept_id DESC LIMIT 1
SELECT MAX(concept.concept_id) AS concept_id__max FROM concept

Leave a comment