191
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);
45
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.
- [Django]-How to delete project in django
- [Django]-Django abstract models versus regular inheritance
- [Django]-Django: TemplateDoesNotExist (rest_framework/api.html)
35
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.
- [Django]-Django Model MultipleChoice
- [Django]-Django rest framework, use different serializers in the same ModelViewSet
- [Django]-Django – Website Home Page
9
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.
And then reindexed.
- [Django]-Django query get last n records
- [Django]-Embed YouTube video – Refused to display in a frame because it set 'X-Frame-Options' to 'SAMEORIGIN'
- [Django]-Django: Calculate the Sum of the column values through query
8
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.
- [Django]-Create empty queryset by default in django form fields
- [Django]-"Too many values to unpack" Exception
- [Django]-Django template can't see CSS files
5
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.
- [Django]-Django template can't see CSS files
- [Django]-Django – "no module named django.core.management"
- [Django]-How to find out the request.session sessionid and use it as a variable in Django?
3
If you have manually copied the databases, you may be running into the issue described here.
- [Django]-How to pass multiple values for a single URL parameter?
- [Django]-Django: reverse accessors for foreign keys clashing
- [Django]-Django TextField and CharField is stripping spaces and blank lines
3
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.
- [Django]-How do I get the object if it exists, or None if it does not exist in Django?
- [Django]-Django abstract models versus regular inheritance
- [Django]-Filter by property
1
This question was asked about 9 years ago, and lots of people gave their own ways to solve it.
For me, I put unique=True
in my email
custom model field, but while creating superuser I didn’t ask for the email
to be mandatory.
Now after creating a superuser my email field is just saved as blank or Null
. Now this is how I created and saved new user
obj = mymodel.objects.create_user(username='abc', password='abc')
obj.email = 'abc@abc.com'
obj.save()
It just threw the error saying duplicate-key-value-violates
in the first line because the email was set to empty by default which was the same with the admin user. Django spotted a duplicate !!!
Solution
- Option1: Make email mandatory while creating any user (for superuser as well)
- Option2: Remove
unique=True
and run migrations - Option3: If you don’t know where are the duplicates, you either drop the column or you can clear the database using
python manage.py flush
It is highly recommended to know the reason why the error occurred in your case.
- [Django]-Django self-referential foreign key
- [Django]-Find Monday's date with Python
- [Django]-TemplateDoesNotExist – Django Error
0
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
- [Django]-Alowing 'fuzzy' translations in django pages?
- [Django]-Get count of related model efficiently in Django
- [Django]-Django admin ManyToMany inline "has no ForeignKey to" error
0
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.
- [Django]-How to get a favicon to show up in my django app?
- [Django]-How can I return HTTP status code 204 from a Django view?
- [Django]-Filter Queryset on empty ImageField
0
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);
- [Django]-How to add custom search box in Django-admin?
- [Django]-You are trying to add a non-nullable field 'new_field' to userprofile without a default
- [Django]-How can I handle Exceptions raised by dango-social-auth?
0
Based on Paolo Melchiorre’s answer, I wrote a chunk as a function to be called before any .save()
from django.db import connection
def setSqlCursor(db_table):
sql = """SELECT pg_catalog.setval(pg_get_serial_sequence('"""+db_table+"""', 'id'), MAX(id)) FROM """+db_table+""";"""
with connection.cursor() as cursor:
cursor.execute(sql)
- [Django]-How to use MySQLdb with Python and Django in OSX 10.6?
- [Django]-Login Page by using django forms
- [Django]-Django Rest Framework – Could not resolve URL for hyperlinked relationship using view name "user-detail"
0
This is the right statement. Mostly, It happens when we insert rows with id field.
SELECT setval('tablename_id_seq', (SELECT MAX(id) FROM tablename));
- [Django]-Visual Studio Code: Intellisense not working
- [Django]-How to use 'select_related' with get_object_or_404?
- [Django]-How do I install an old version of Django on virtualenv?