Home > Software engineering >  Django-rearart sequence of postgres id field with 0 instead of 1
Django-rearart sequence of postgres id field with 0 instead of 1

Time:12-17

I want to reset the sequence of a "postgresql" table to start from "0" in a django application.

My code is:

views.py

sequence_sql = connection.ops.sequence_reset_sql(no_style(), [ModelName])
with connection.cursor() as cursor:
      for sql in sequence_sql:
            cursor.execute(sql)
print("sequence reset")

The sequence is restarted successfully; but with "1". I want the sequence to start from 0.

How can I achieve that?

CodePudding user response:

To reset the sequence of a PostgreSQL table in a Django application, you can use the RawSQL method in the Django ORM to execute a raw SQL statement. Here is an example of how you can reset the sequence of a table named table_name to start from 0:

from django.db import connection

def reset_sequence(table_name):
    with connection.cursor() as cursor:
        cursor.execute(f"ALTER SEQUENCE {table_name}_id_seq RESTART WITH 1")

This will execute the ALTER SEQUENCE statement, which will reset the sequence to start from 1. If you want the sequence to start from 0, you can simply change the RESTART WITH value to 0.

Note that this will only work if the primary key of the table is a serial column and is using a sequence to generate its values. If the primary key is not a serial column or is not using a sequence, this method will not work.

It's also important to note that resetting the sequence will not reset the primary key values of the rows that are already in the table. It will only affect the values of the primary key for new rows that are inserted into the table after the sequence has been reset.

  • Related