Django object creation and Postgres Sequences

前端 未结 2 1191
一生所求
一生所求 2021-02-09 14:57

I have an import script which runs a series of commands to get things from one Postgres DB to another, both running the same Django codebase. For the most part, it uses ./manage

相关标签:
2条回答
  • 2021-02-09 15:22

    The autoincrement fields works, but yo must make the query like

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

    without the id field, this is autocalculated with the database.

    0 讨论(0)
  • 2021-02-09 15:25

    everything works fine. django's create() has nothing to do with sequence incementation directly. briefly:

    • postgresql auto incrementing ('serial' type) is just a shortcut of 'create sequence + create integer field with sequence value as default'
    • django's autofield primary key (id integer if not specified else by you) just creates a serial field
    • when you specify the id manually, postgres inserts the value into the database. when you specify a value, it omits the 'default' parameter, which is a proper behavior.

    so, if you want your inserts to increment the sequence in a way of your choice, you need to manually change the sequence value using SELECT setval('sequence_name', int_value); otherwise leave it null and it will increment automatically - select the current val and increment it +1 (if not specified differently in the sequence definition).

    another idea is you create the object and then update the id (of course it can't be already used) and in the end set the sequence value to the max id.

    0 讨论(0)
提交回复
热议问题