Last active
January 11, 2022 09:49
-
-
Save kissgyorgy/6110380 to your computer and use it in GitHub Desktop.
Django: Get next primary key for object.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from djangobb_forum.models import Post | |
from django.db.models import Max | |
# id__max is None if there are no Posts in the database | |
id_max = Post.objects.all().aggregate(Max('id'))['id__max'] | |
id_next = id_max + 1 if id_max else 1 |
So far I've really only seen database specific solutions. The following works for PostgreSQL.
def get_next_id(model_class):
from django.db import connection
cursor = connection.cursor()
cursor.execute( "select nextval('%s_id_seq')" % \
model_class._meta.db_table)
row = cursor.fetchone()
cursor.close()
return row[0]
This following snippet works for MySQL.
https://djangosnippets.org/snippets/1415/
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The problem with this is that if several functions call this, they will get the same ID. The best solution will involve invoking the database's next sequence function so that the ID that is returned is only returned once.