Skip to content

Instantly share code, notes, and snippets.

@kissgyorgy
Last active January 11, 2022 09:49
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save kissgyorgy/6110380 to your computer and use it in GitHub Desktop.
Save kissgyorgy/6110380 to your computer and use it in GitHub Desktop.
Django: Get next primary key for object.
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
@jaywhy13
Copy link

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.

@jaywhy13
Copy link

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