jeudi 7 avril 2016

In Django model how can I create a field that resets to 1 on flush?

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.

Aucun commentaire:

Enregistrer un commentaire