Skip to content

Instantly share code, notes, and snippets.

@kissgyorgy
Last active January 11, 2022 09:49
Show Gist options
  • 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

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