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
- [Django]-Django connect mysql problem, NameError: name '_mysql' is not defined
- [Django]-Django ManyToMany field returns None but it has related records
- [Django]-Import data into Django model with existing data?
- [Django]-Rails or Django style routing in Perl
- [Django]-Use Django-Storages with IAM Instance Profiles
- [Django]-How can you use Django template tags in a Jinja2 template?
- [Django]-"global name '_' is not defined" during raising ValidationError
- [Django]-Custom the `on_delete` param function in Django model fields
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
Source:stackexchange.com