IntegrityError duplicate key value violates unique constraint - django/postgres

后端 未结 11 1052
清歌不尽
清歌不尽 2020-11-28 18:44

I\'m following up in regards to a question that I asked earlier in which I sought to seek a conversion from a goofy/poorly written mysql query to postgresql. I believe I suc

11条回答
  •  野性不改
    2020-11-28 19:36

    It appears to be a known difference of behaviour between the MySQL and SQLite (they update the next available primary key even when inserting an object with an explicit id) backends, and other backends like Postgres, Oracle, ... (they do not).

    There is a ticket describing the same issue. Even though it was closed as invalid, it provides a hint that there is a Django management command to update the next available key.

    To display the SQL updating all next ids for the application MyApp:

    python manage.py sqlsequencereset MyApp
    

    In order to have the statement executed, you can provide it as the input for the dbshell management command. For bash, you could type:

    python manage.py sqlsequencereset MyApp | python manage.py dbshell
    

    The advantage of the management commands is that abstracts away the underlying DB backend, so it will work even if later migrating to a different backend.

提交回复
热议问题