Last active
December 23, 2022 07:46
-
-
Save devhero/22c702fea284b3eaed3a3d643bd20b17 to your computer and use it in GitHub Desktop.
django postgres next/reset sequence id - https://gist.github.com/kissgyorgy/6110380 - http://stackoverflow.com/questions/244243/how-to-reset-postgres-primary-key-sequence-when-it-falls-out-of-sync
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 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
A bit shorter solution. Also it creates sequence if it does not exists. It was tested on PostgreSQL.