Skip to content

Instantly share code, notes, and snippets.

@bay007
Forked from kissgyorgy/get_next_primary_key.py
Created August 16, 2020 06:31
Show Gist options
  • Save bay007/b76c2dcf3315dc447cd70706d949e867 to your computer and use it in GitHub Desktop.
Save bay007/b76c2dcf3315dc447cd70706d949e867 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment