IntegrityError duplicate key value violates unique constraint - django/postgres

后端 未结 11 990
清歌不尽
清歌不尽 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:23

    I encountered this error because I was passing extra arguments to the save method in the wrong way.

    For anybody who encounters this, try forcing UPDATE with:

    instance_name.save(..., force_update=True)
    

    If you get an error that you cannot pass force_insert and force_update at the same time, you're probably passing some custom arguments the wrong way, like I did.

    0 讨论(0)
  • 2020-11-28 19:23

    I was getting a similar issue and nothing seemed to be working. If you need the data (ie cant exclude it when doing dump) make sure you have turned off (commented) any post_save receivers. I think the data would be imported but it would create the same model again because of these. Worked for me.

    0 讨论(0)
  • 2020-11-28 19:25

    If you have manually copied the databases, you may be running into the issue described here.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-28 19:39

    I was getting the same error as the OP.

    I had created some Django models, created a Postgres table based on the models, and added some rows to the Postgres table via Django Admin. Then I fiddled with some of the columns in the models (changing around ForeignKeys, etc.) but had forgotten to migrate the changes.

    Running the migration commands solved my problem, which makes sense given the SQL answers above.

    To see what changes would be applied, without actually applying them:
    python manage.py makemigrations --dry-run --verbosity 3

    If you're happy with those changes, then run:
    python manage.py makemigrations

    Then run:
    python manage.py migrate

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