Creating a Django Object and Postgres Sequence

I have an import script that runs a series of commands to get things from one Postgres database to another, both of which work with the same Django code base. For the most part, he uses. /manage.py loaddata to copy, but some objects require additional processing, and I use the Django objects.create () method in a user script to copy data. In this case, I specify the ID, i.e.

MyObject.objects.create(id = 2, title = 'foo') 

As soon as the script is executed, I notice that Postgres SEQUENCE is wrong in the tables where I did objects.create (). I., it was 50 before import, and another 50 after, although the table now has 150 objects. This, of course, leads to errors when creating new objects, because it tries to use an existing ID (in all these tables, the identifier is simply a field for automatically increasing the number of vanilla). However, tables filled with. /manage.py loaddata, look normal.

I know that I can manually reset these tables with Django./manage.py sqlsequenreset, but I'm curious why the sequence seems to get out of impact in the first place. Does object.create () increase it? Can I ignore something obvious?

+6
django postgresql
source share
2 answers

everything is working fine. django create () has nothing to do with the paste sequence. Briefly:

  • postgresql auto incrementing ("serial" type) is just a shortcut to 'create sequence + create integer field with default sequence value'
  • The django autofield primary key (id integer, unless otherwise specified by you) simply creates a serial field
  • when specifying an identifier manually, postgres inserts the value into the database. when you specify a value, it omits the default parameter, which is the correct behavior.

therefore, if you want your inserts to increase the sequence according to your choice, you need to manually change the sequence value using SELECT setval ('sequence_name', int_value); otherwise, leave it zero and it will automatically increase - select the current val and add it +1 (unless otherwise specified in the sequence definition).

Another idea is that you create an object and then update the identifier (of course, it cannot be used already) and at the end sets the sequence value for the maximum id.

+12
source share

Autoincrement fields work, but yo should make a request like

 MyObject.objects.create(title='foo') 

without an id field, this is automatically determined using the database.

+2
source share

All Articles