IntegrityError duplicate key value violates unique constraint - django/postgres

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

    I had an existing table in my "inventory" app and I wanted to add new records in Django admin and I got this error:

    Duplicate key value violates unique constraint "inventory_part_pkey" DETAIL: Key (part_id)=(1) already exists.

    As mentioned before, I run the code below to get the SQL command to reset the id-s:

    python manage.py sqlsequencereset inventory
    

    Piping the python manage.py sqlsequencereset inventory | python manage.py dbshell to the shell was not working

    • So I copied the generated raw SQL command
    • Then opened pgAdmin3 https://www.pgadmin.org for postgreSQL and opened my db
    • Clicked on the 6. icon (Execute arbitrary SQL queries)
    • Copied the statement what was generated

    In my case the raw SQL command was:

    BEGIN;
    SELECT setval(pg_get_serial_sequence('"inventory_signup"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "inventory_signup";
    SELECT setval(pg_get_serial_sequence('"inventory_supplier"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "inventory_supplier";
    COMMIT;
    

    Executed it with F5.

    This fixed everything.

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

    You just have to go to pgAdmin III and there execute your script with the name of the table:

    SELECT setval('tablename_id_seq', (SELECT MAX(id) FROM tablename)+1);
    
    0 讨论(0)
  • 2020-11-28 19:18

    The solution is that you need to resync your primary key fields as reported by "Hacking Life" who wrote an example SQL code but, as suggested by "Ad N" is better to run the Django command sqlsequencereset to get the exact SQL code that you can copy and past or run with another command.

    As a further improvement to these answers I would suggest to you and other reader to dont' copy and paste the SQL code but, more safely, to execute the SQL query generated by sqlsequencereset from within your python code in this way (using the default database):

    from django.core.management.color import no_style
    from django.db import connection
    
    from myapps.models import MyModel1, MyModel2
    
    
    sequence_sql = connection.ops.sequence_reset_sql(no_style(), [MyModel1, MyModel2])
    with connection.cursor() as cursor:
        for sql in sequence_sql:
            cursor.execute(sql)
    

    I tested this code with Python3.6, Django 2.0 and PostgreSQL 10.

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

    If you want to reset the PK on all of your tables, like me, you can use the PostgreSQL recommended way:

    SELECT 'SELECT SETVAL(' ||
           quote_literal(quote_ident(PGT.schemaname) || '.' || quote_ident(S.relname)) ||
           ', COALESCE(MAX(' ||quote_ident(C.attname)|| '), 1) ) FROM ' ||
           quote_ident(PGT.schemaname)|| '.'||quote_ident(T.relname)|| ';'
    FROM pg_class AS S,
         pg_depend AS D,
         pg_class AS T,
         pg_attribute AS C,
         pg_tables AS PGT
    WHERE S.relkind = 'S'
        AND S.oid = D.objid
        AND D.refobjid = T.oid
        AND D.refobjid = C.attrelid
        AND D.refobjsubid = C.attnum
        AND T.relname = PGT.tablename
    ORDER BY S.relname;
    

    After running this query, you will need to execute the results of the query. I typically copy and paste into Notepad. Then I find and replace "SELECT with SELECT and ;" with ;. I copy and paste into pgAdmin III and run the query. It resets all of the tables in the database. More "professional" instructions are provided at the link above.

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

    This happend to me - it turns out you need to resync your primary key fields in Postgres. The key is the SQL statement:

    SELECT setval('tablename_id_seq', (SELECT MAX(id) FROM tablename)+1);
    
    0 讨论(0)
  • 2020-11-28 19:22

    In addition to zapphods answer:

    In my case the indexing was indeed incorrect, since I had deleted all migrations, and the database probably 10-15 times when developing as I wasn't in the stage of migrating anything.

    I was getting an IntegrityError on finished_product_template_finishedproduct_pkey

    Reindex the table and restart runserver:

    I was using pgadmin3 and for whichever index was incorrect and throwing duplicate key errors I navigated to the constraints and reindexed.

    enter image description here

    And then reindexed.

    enter image description here

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