django.db.utils.IntegrityError: 违反唯一约束条件 "spirit_category_category_pkey" 的重复键值。

9

错误

我正在使用django和Spirit构建一个网站。在测试过程中,当我向名为spirit_category_category的表中插入新数据时,出现了以下错误:

django.db.utils.IntegrityError: duplicate key value violates unique constraint "spirit_category_category_pkey"
DETAIL:  Key (id)=(1) already exists.

请注意,表中已经有其他两条记录,其id分别为12。因此,插入Key(id)=(1)肯定行不通。但执行的sql语句并没有包括id字段。也就是说,Key (id)=(1)是由PostgreSQL自动生成的,那么它为什么会生成一个已经存在的id呢?

原因

为了找出原因,我在PostgreSQL中运行了以下命令:
test_spiritdb=# select start_value, last_value, max_value from spirit_category_category_id_seq;
 start_value | last_value |      max_value      
-------------+------------+---------------------
           1 |          1 | 9223372036854775807
(1 row)

基本上,last_value1,所以postgresql每次都会生成Key (id)=(1)。我尝试将其更改为3,一切正常。

test_spiritdb=# alter sequence spirit_category_category_id_seq restart with 3;

我不知道如何为测试修复它

测试通过了。但是这只是一个测试,所以修改测试表是没有意义的,因为测试数据库将在每次测试时被删除并重新创建,所以下一次测试仍将失败,因为last_value仍将生成为1。那么我想知道为什么django/postgresql会为last_value生成这样一个异常值?如何修复它?如果有帮助,以下是category的模型和迁移。

models.py

# -*- coding: utf-8 -*-

from __future__ import unicode_literals

from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.core.urlresolvers import reverse
from django.conf import settings

from .managers import CategoryQuerySet
from ..core.utils.models import AutoSlugField

class Category(models.Model):

    parent = models.ForeignKey('self', verbose_name=_("category parent"), null=True, blank=True)

    title = models.CharField(_("title"), max_length=75)
    slug = AutoSlugField(populate_from="title", db_index=False, blank=True)
    description = models.CharField(_("description"), max_length=255, blank=True)
    is_global = models.BooleanField(_("global"), default=True,
                                    help_text=_('Designates whether the topics will be'
                                                'displayed in the all-categories list.'))
    is_closed = models.BooleanField(_("closed"), default=False)
    is_removed = models.BooleanField(_("removed"), default=False)
    is_private = models.BooleanField(_("private"), default=False)

    # topic_count = models.PositiveIntegerField(_("topic count"), default=0)

    objects = CategoryQuerySet.as_manager()

    class Meta:
        ordering = ['title', 'pk']
        verbose_name = _("category")
        verbose_name_plural = _("categories")

    def get_absolute_url(self):
        if self.pk == settings.ST_TOPIC_PRIVATE_CATEGORY_PK:
            return reverse('spirit:topic:private:index')
        else:
            return reverse('spirit:category:detail', kwargs={'pk': str(self.id), 'slug': self.slug})

    @property
    def is_subcategory(self):
        if self.parent_id:
            return True
        else:
            return False

0001_initial.py

# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models, migrations
import spirit.core.utils.models


class Migration(migrations.Migration):

    dependencies = [
    ]

    operations = [
        migrations.CreateModel(
            name='Category',
            fields=[
                ('id', models.AutoField(primary_key=True, verbose_name='ID', serialize=True, auto_created=True)),
                ('title', models.CharField(verbose_name='title', max_length=75)),
                ('slug', spirit.core.utils.models.AutoSlugField(db_index=False, populate_from='title', blank=True)),
                ('description', models.CharField(verbose_name='description', max_length=255, blank=True)),
                ('is_closed', models.BooleanField(verbose_name='closed', default=False)),
                ('is_removed', models.BooleanField(verbose_name='removed', default=False)),
                ('is_private', models.BooleanField(verbose_name='private', default=False)),
                ('parent', models.ForeignKey(null=True, verbose_name='category parent', to='spirit_category.Category', blank=True)),
            ],
            options={
                'ordering': ['title', 'pk'],
                'verbose_name': 'category',
                'verbose_name_plural': 'categories',
            },
        ),
    ]

0002_auto_20150728_0442.py

# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models, migrations
from django.conf import settings


def default_categories(apps, schema_editor):
    Category = apps.get_model("spirit_category", "Category")

    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"
        )


class Migration(migrations.Migration):

    dependencies = [
        ('spirit_category', '0001_initial'),
    ]

    operations = [
        migrations.RunPython(default_categories),
    ]

0003_category_is_global.py

# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models, migrations


class Migration(migrations.Migration):

    dependencies = [
        ('spirit_category', '0002_auto_20150728_0442'),
    ]

    operations = [
        migrations.AddField(
            model_name='category',
            name='is_global',
            field=models.BooleanField(default=True, help_text='Designates whether the topics will bedisplayed in the all-categories list.', verbose_name='global'),
        ),
    ]
4个回答

4

经过大量调试,我终于找到了解决方案。问题出在我试图插入两个带有指定 id 的另外两个 categories,这会导致postgresql停止增加相关sequencelast_value。如下所示:

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"
    )

修复这个问题很简单,要么手动在django中更改last_value,要么只需不指定id,即删除以下行:
....
pk=settings.ST_TOPIC_PRIVATE_CATEGORY_PK,
....
pk=settings.ST_UNCATEGORIZED_CATEGORY_PK,
....

我想如果您让Django来管理id,那么在插入新数据时自己指定id可能不是一个好主意。


0

我认为问题不在于你的迁移。

你正在尝试添加多个相同的 spirit_category_category 对象,如果在 Django 测试套件中没有正确配置,将触发相同的自增 id。一种选择是识别冲突测试并将它们移动到单独的 TestCase 类中(因为 setUp 会为您清空数据库)。

另一个选择是使用类似 Factory Boy 的库来创建您的模型实例,这将有助于避免这样的冲突。


我确实将相同的 id 插入了表中,就像你所说的那样。我删除了 id 部分,一切又恢复正常了。谢谢! - Searene

0

我遇到了同样的问题,但我需要保留ID,因为我正在从另一个服务器恢复数据并保持关系等。 我的解决方案是在迁移文件中添加另一个命令,在插入项目后运行该命令并重置涉及表的数据库序列。

要获取重置表序列的命令,您可以运行 python manage.py sqlsequencereset spirit,如 https://docs.djangoproject.com/en/1.9/ref/django-admin/#sqlsequencereset 所述

然后在您的迁移0002_auto_20150728_0442.py 文件中添加:

from django.db connection

def reset_spirit_pk_sequence(apps, schema_editor):
    with connection.cursor() as cursor:
        cursor.execute("RESULT_FROM_SQLRESETSEQUENCE")
    row = cursor.fetchone()

...
...

operations = [
    migrations.RunPython(default_categories),
    migrations.RunPython(reset_spirit_pk_sequence),
]

请注意,将RESULT_FROM_SQLRESETSEQUENCE替换为您从与您遇到问题的表相关的manage.py sqlresetsequence中获取的命令行(使用\转义内部")的行。

0
在一个测试中,我的代码尝试保存一行记录但是没有传递id(主键),然而我却收到了以下错误信息:
django.db.utils.IntegrityError: duplicate key value violates unique constraint ...
DETAIL:  Key (id)=(1) already exists. 

我解决了这个问题,方法如下:

iOneMore = Model.objects.last().id + 1
oNew = Model( id = iOneMore, col1 = string1, col2 = string2 )
oNew.save()

问题已解决,不再出现错误。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接