1

my model :

class User(models.Model) :
    """Model for a Person"""
    email = models.EmailField(unique=True)
    groups = models.IntegerField(default=0)
    name = models.CharField(max_length=254, blank=True, null=True)
    phone = models.CharField(max_length=10, blank=True, null=True)
    sex = models.CharField(max_length=7, blank=True, null=True)

This class already has an id primary key. I have following entries in my database:

In [23]: temp = User.objects.all()

In [24]: temp
Out[24]: [<User: testid@test.com>, <User: test2@test.com>]

In [25]: temp[0].id
Out[25]: 15

In [26]: temp[1].id
Out[26]: 16

Now When I run :

python manage.py flush

Here is how my database looks:

In [27]: User.objects.all()
Out[27]: []

Now when I add a new user it has id after 16 as from previous output.

In [28]: x = User(email="test3@faf.com")

In [29]: x.save()

In [30]: x.id
Out[30]: 17

I have read the answers Stack Overflow answer, that primary key continue after where they have left. I am also fine with that and do not want to alter this behaviour. Instead, what I want is to create another field that starts again from 1 after the db has been flushed. I have some logic that relies on this behaviour. Please tell me a way so that I can create an Integer Type auto-increment field which resets to 1 on flush.

I am using sqlite3 as database.

Community
  • 1
  • 1
aks
  • 8,796
  • 11
  • 50
  • 78

1 Answers1

1

you can run this command in manage.py dbshell

delete from your_table;    
delete from sqlite_sequence where name='your_table';

this will reset the auto increment , and you can easily convert this into a command . here is more info about it.

Which would look something like this

from django.core.management.base import BaseCommand

class Command(BaseCommand):

    def add_arguments(self, parser):

        parser.add_argument('table_name',type=str)

    def handle(self, *args, **options):

        table_name = options['table_name']
        cursor = connection.cursor()
        cursor.execute("delete from {}".format(table_name))
        cursor.execute("delete from from sqlite_sequence where name='{}'".format(table_name))

Also keep in mind the table name would be app_name+_+model_name. So for eg. if you have an app named work and a model named employee inside then the default table name in the sqlite will be work_employee.

Note : i havent tested the code.

GIRISH RAMNANI
  • 614
  • 6
  • 18