django.db.utils.IntegrityError: duplicate key value violates unique constraint "spirit_category_category_pkey"
After lots of debugging, I finally found the solution. The reason is that I was trying to insert two another categories
with specified ids, which would cause postgresql stop increasing the last_value
of the relative sequence
. Just as follows:
0002_auto_20150728_0442.py
if not Category.objects.filter(pk=settings.ST_TOPIC_PRIVATE_CATEGORY_PK).exists():
Category.objects.create(
pk=settings.ST_TOPIC_PRIVATE_CATEGORY_PK,
title="Private",
slug="private",
is_private=True
)
if not Category.objects.filter(pk=settings.ST_UNCATEGORIZED_CATEGORY_PK).exists():
Category.objects.create(
pk=settings.ST_UNCATEGORIZED_CATEGORY_PK,
title="Uncategorized",
slug="uncategorized"
)
The way to fix this is simple, either change the last_value
manually in django
, or just don't specify the id, i.e. remove the following lines:
....
pk=settings.ST_TOPIC_PRIVATE_CATEGORY_PK,
....
pk=settings.ST_UNCATEGORIZED_CATEGORY_PK,
....
I guess if you let django undertake the task of managing id
, it may not be a good idea to specify the id
yourself when inserting new data.