Skip to content

Instantly share code, notes, and snippets.

@devhero
Last active December 23, 2022 07:46
Show Gist options
  • Save devhero/22c702fea284b3eaed3a3d643bd20b17 to your computer and use it in GitHub Desktop.
Save devhero/22c702fea284b3eaed3a3d643bd20b17 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))
@mark-mishyn
Copy link

mark-mishyn commented Jun 9, 2021

def set_sequence(model):
    max_id = model.objects.aggregate(m=Max('id'))['m']
    seq = max_id or 1
    with connection.cursor() as cursor:
        cursor.execute("SELECT setval(pg_get_serial_sequence(%s,'id'), %s);", [model._meta.db_table, seq])

A bit shorter solution. Also it creates sequence if it does not exists. It was tested on PostgreSQL.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment