Skip to content

Instantly share code, notes, and snippets.

@ar7n
Forked from devhero/django_pg_sequence.py
Created October 4, 2019 12:14
Show Gist options
  • Save ar7n/b16c2fefed17b6a8319d9826c763fd84 to your computer and use it in GitHub Desktop.
Save ar7n/b16c2fefed17b6a8319d9826c763fd84 to your computer and use it in GitHub Desktop.
from django.db import connection
def idseq(model_class):
return '{}_id_seq'.format(model_class._meta.db_table)
def get_next_id(model_class):
cursor = connection.cursor()
sequence = idseq(model_class)
cursor.execute("select nextval('%s')" % sequence)
row = cursor.fetchone()
cursor.close()
return row[0]
def reset_sequence(model_class, value=1):
cursor = connection.cursor()
sequence = idseq(model_class)
cursor.execute("ALTER SEQUENCE {} RESTART WITH {};".format(sequence, value))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment