poncho
poncho

Reputation: 3

django tacking back model id?

I have the following list of ids

If I delete id 2 and then I insert a new value, it takes id 5.
Is it possible to re-assign automatically id 2?

Upvotes: 0

Views: 123

Answers (1)

Austin Phillips
Austin Phillips

Reputation: 15746

The primary key of a model in Django is generally represented by an auto-incrementing field which is handled by the database layer. eg In MySQL, the AUTO_INCREMENT option will be added to the primary key.

This provides an efficient way for the database layer to assign a unique id to each record. Without significant change to Django it won't be possible to have it not use an AUTO_INCREMENT type.

Instead, you will probably need to add a field which is under your control which you ensure manually does not contain any gaps. from django.db import models

class MyModel(models.Model):
    my_id = models.IntegerField(unique=True)

It would then be up to you to assign a value to my_id before saving that represented your sequence which doesn't include gaps. Finding what the next my_id should be on insert is probably not trivial and may not be easy to do efficiently through the Django ORM. See How to find gaps in sequential numbering in mysql? for some ideas.

Renumbering the original id may prove problematic, especially for any data that was created that referenced the original id.

Upvotes: 2

Related Questions