本文介绍了django.db.utils.IntegrityError:(1062,“重复条目”用于密钥'slug'))的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试跟随tangowithdjango书,必须添加一个s子来更新类别表。但是,尝试迁移数据库后,我收到错误。

I'm trying to follow the tangowithdjango book and must add a slug to update the category table. However I'm getting an error after trying to migrate the databases.

我没有为slug提供默认值,所以Django要我提供一个,并且正如本书指示的那样我输入。

I didn't provide a default value for the slug, so Django asked me to provide one and as the book instructed I type in ''.

值得注意的是,不是像原来的书一样使用sqlite,而是使用mysql。

It's worth noticing that instead of using sqlite as in the original book I'm using mysql.

models.py
from django.db import models
from django.template.defaultfilters import slugify

# Create your models here.
class Category(models.Model):
      name = models.CharField(max_length=128, unique=True)
      views = models.IntegerField(default=0)
      likes = models.IntegerField(default=0)
      slug = models.SlugField(unique=True)

      def save(self, *args, **kwargs):
              self.slug = slugify(self.name)
              super(Category, self).save(*args, **kwargs)

       class Meta:
              verbose_name_plural = "Categories"

       def __unicode__(self):
              return self.name

class Page(models.Model):
        category = models.ForeignKey(Category)
        title = models.CharField(max_length=128)
        url = models.URLField()
        views = models.IntegerField(default=0)

        def __unicode__(self):
                return self.title

命令提示符

sudo python manage.py migrate       
Operations to perform:
   Apply all migrations: admin, rango, contenttypes, auth, sessions
Running migrations:
  Applying rango.0003_category_slug...Traceback (most recent call last):
  File "manage.py", line 10, in <module>
    execute_from_command_line(sys.argv)
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 385, in  execute_from_command_line
utility.execute()
 File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 377, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 288, in run_from_argv
self.execute(*args, **options.__dict__)
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 338, in execute
output = self.handle(*args, **options)
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/commands/migrate.py", line 160, in handle
executor.migrate(targets, plan, fake=options.get("fake", False))
  File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/executor.py", line 63, in migrate
self.apply_migration(migration, fake=fake)
  File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/executor.py", line 97, in apply_migration
migration.apply(project_state, schema_editor)
  File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/migration.py", line 107, in apply
operation.database_forwards(self.app_label, schema_editor, project_state, new_state)
  File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/operations/fields.py", line 37, in database_forwards
field,
  File "/usr/local/lib/python2.7/dist-packages/django/db/backends/mysql/schema.py", line 42, in add_field
super(DatabaseSchemaEditor, self).add_field(model, field)
  File "/usr/local/lib/python2.7/dist-packages/django/db/backends/schema.py", line 411, in add_field
self.execute(sql, params)
  File "/usr/local/lib/python2.7/dist-packages/django/db/backends/schema.py", line 98, in execute
cursor.execute(sql, params)
  File "/usr/local/lib/python2.7/dist-packages/django/db/backends/utils.py", line 81, in execute
return super(CursorDebugWrapper, self).execute(sql, params)
  File "/usr/local/lib/python2.7/dist-packages/django/db/backends/utils.py", line 65, in execute
return self.cursor.execute(sql, params)
  File "/usr/local/lib/python2.7/dist-packages/django/db/utils.py", line 94, in __exit__
six.reraise(dj_exc_type, dj_exc_value, traceback)
  File "/usr/local/lib/python2.7/dist-packages/django/db/backends/utils.py", line 65, in execute
return self.cursor.execute(sql, params)
  File "/usr/local/lib/python2.7/dist-packages/django/db/backends/mysql/base.py", line 128, in execute
return self.cursor.execute(query, args)
  File "/usr/local/lib/python2.7/dist-packages/MySQLdb/cursors.py", line 205, in execute
self.errorhandler(self, exc, value)
  File "/usr/local/lib/python2.7/dist-packages/MySQLdb/connections.py", line 36, in defaulterrorhandler
raise errorclass, errorvalue
django.db.utils.IntegrityError: (1062, "Duplicate entry '' for key 'slug'")


推荐答案

分析一下:


  1. slug 字段与 unique = True ,这意味着:每个记录必须具有不同的值,不能有两个记录在 slug

  2. 中具有相同的值您正在创建迁移:django要求您存在于数据库中的字段的默认值,因此您提供了'(空字符串)作为该值。

  3. 现在django正在尝试迁移您的数据库。在数据库中我们至少有2条记录

  4. 首先记录被迁移,slug列用空字符串填充。这很好,因为没有其他记录在 slug 字段中有空字符串

  5. 第二个记录被迁移,slug列填充有空字符串。因为第一条记录在 slug 字段中已经有空字符串,所以失败。异常被提升,迁移中止。

  1. You're adding slug field with unique = True, that means: each record must have different value, there can't be two records with same value in slug
  2. You're creating migration: django asks you for default value for fields that exists already in database, so you provided '' (empty string) as that value.
  3. Now django is trying to migrate your database. In database we have at least 2 records
  4. First record is migrated, slug column is populated with empty string. That's good because no other record is having empty string in slug field
  5. Second record is migrated, slug column is populated with empty string. That fails, because first record already have empty string in slug field. Exception is raised and migration is aborted.

这就是为什么您的迁移失败。所有你应该做的是编辑迁移,复制 migrations.AlterField 操作两次,在第一个操作中remove unique = True。在这些操作之间,您应该将 migrations.RunPython 操作并提供2个参数: generate_slugs migrations.RunPython.noop

That's why your migration fails. All you should do is to edit migration, copy migrations.AlterField operation twice, in first operation remove unique=True. Between that operations you should put migrations.RunPython operation and provide 2 parameters into that: generate_slugs and migrations.RunPython.noop.

现在您必须在迁移功能之前创建迁移类之前,将该函数命名为 generate_slugs 。函数应该有两个参数: apps schema_editor 。在你的函数放在第一行:

Now you must create inside your migration function BEFORE migration class, name that function generate_slugs. Function should take 2 arguments: apps and schema_editor. In your function put at first line:

Category = apps.get_model('your_app_name', 'Category')

现在使用 Category.objects.all()循环所有的记录,并为他们提供独特的s。。

and now use Category.objects.all() to loop all your records and provide unique slug for each of them.

这篇关于django.db.utils.IntegrityError:(1062,“重复条目”用于密钥'slug'))的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-19 10:39