0

I have created 31 objects in my database. Now, for some reason, if I create a new object through the Django admin page, the new object will have an id of 33. Now, suppose I change I change its id and then delete it. If I try to create a new object, it's id will be 34. So, the id is always shifted by 2. I'm very new to databases and Django, is there any reason for behaving like this? Thanks

Note: I didn't upload any code, because I don't think that's the problem...

Antoni4040
  • 2,297
  • 11
  • 44
  • 56
  • 1
    What do you mean *"change its id"*? You shouldn't be doing that directly. The default `id` field is an autonumber, you shouldn't be reusing ids from deleted objects. – jonrsharpe Jun 24 '15 at 10:32
  • What do you mean? When an object is deleted, I can't use it's id? – Antoni4040 Jun 24 '15 at 10:36
  • You certainly *shouldn't*, and the defaults won't let you. Why would you want to? The new object is *a different object*, why would it share the ID?! – jonrsharpe Jun 24 '15 at 10:36
  • Why share it? One object is gone, there's a new one. My object ids go like this: 30,31,34,35... Now, I have an algorithm that depends on those ids to give a result, and when there's an empty place, it can't find anything and return an error. – Antoni4040 Jun 24 '15 at 10:39
  • 2
    Then the problem is with your algorithm. You should **not** expect the IDs in the table to be consecutive. What if an insert fails, or you roll back a deletion? See e.g. http://stackoverflow.com/q/16582704/3001761 – jonrsharpe Jun 24 '15 at 10:40
  • OK, then I'll change it – Antoni4040 Jun 24 '15 at 10:53

1 Answers1

1

By default, the id is an integer that is always incremented at the creation of an object. It is also incremented such that ids of deleted objects are never used again.

The incrementation is handled by the database itself, not Django. For example, with PostgreSQL, the corresponding database field corresponding the "id" has the "PRIMARY KEY" constraint. It basically means that the field should be not null, and with no duplicates. Moreover the field will be associated with a sequence, that stores the id to use for the next row creation. To change this number, run this in the database shell:

ALTER SEQUENCE yourobjectstable_id_seq RESTART WITH 1234;

However, as emphasized in the comments to your question, this is something you should not do: it is better to keep the "uniqueness" feature of the primary key, even for deleted objects, since other tables may use the id to refer to a row in your main table.

mimo
  • 2,469
  • 2
  • 28
  • 49