django.db.utils.IntegrityError: (1062, "Duplicate entry '' for key 'slug'")
django.db.utils.IntegrityError: (1062, "Duplicate entry '' for key 'slug'")
我正在尝试学习 tangowithdjango 这本书,必须添加一个 slug 来更新类别 table。但是,我在尝试迁移数据库后遇到错误。
http://www.tangowithdjango.com/book17/chapters/models_templates.html#creating-a-details-page
我没有为 slug 提供默认值,所以 Django 要求我提供一个默认值,并且按照书上的说明我输入了 ''。
值得注意的是,我没有像原书中那样使用 sqlite,而是使用 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'")
您的 table 中的行必须已经带有空 slug,这违反了您创建的 mysql 唯一约束。您可以通过 运行ning manage.py dbshell
手动更新它们以到达 mysql 客户端,然后更新有问题的行,例如
update table rango_category set slug = name where slug = '';
(假设带有空白 slug 的行有名称)。或者您可以使用
删除行
delete from rango_category where slug = '';
在那之后,您应该可以 运行 您的迁移。
我们一步一步来分析:
- 您正在添加带有
unique = True
的 slug
字段,这意味着:每条记录必须具有不同的值,slug
[= 中不能有两条具有相同值的记录38=]
- 您正在创建迁移:django 要求您为数据库中已存在的字段提供默认值,因此您提供了 ''(空字符串)作为该值。
- 现在 django 正在尝试迁移您的数据库。在数据库中我们至少有 2 条记录
- 迁移了第一条记录,slug 列填充了空字符串。这很好,因为没有其他记录在
slug
字段 中有空字符串
- 第二条记录已迁移,slug 列填充有空字符串。那失败了,因为第一条记录在
slug
字段中已经有空字符串。引发异常并中止迁移。
这就是您迁移失败的原因。您应该做的就是编辑迁移,复制 migrations.AlterField
操作两次,在第一次操作中删除 unique=True。在这些操作之间,您应该放置 migrations.RunPython
操作并为其提供 2 个参数:generate_slugs
和 migrations.RunPython.noop
.
现在您必须在迁移之前在迁移函数内部创建 class,将该函数命名为 generate_slugs
。函数应采用 2 个参数:apps
和 schema_editor
。在你的函数放在第一行:
Category = apps.get_model('your_app_name', 'Category')
现在使用 Category.objects.all()
循环所有记录并为每个记录提供唯一的 slug。
如果您的 table 中有多个类别,那么您不能有 unique=True
和 default=''
,因为那样您将有多个类别 slug=''
.如果您的教程要求这样做,那么这是个糟糕的建议,尽管它可能在 SQLite 中有效。
向模型添加唯一字段的正确方法是:
- 删除当前不起作用的迁移。
- 添加 slug 字段,
unique=False
。创建一个新迁移并 运行 它。
- 为每个类别设置一个独特的 slug。听起来 rango 填充脚本可能会这样做。或者,您可以编写一个迁移来设置 slug,甚至可以在 Django 管理中手动设置它们。
- 将 slug 字段更改为
unique=True
。创建一个新迁移并 运行 它。
如果这太难了,那么您可以从数据库中删除除一个类别之外的所有类别。那么您当前的迁移将 运行 而不会出现唯一约束的问题。您可以稍后再次添加类别。
我正在尝试学习 tangowithdjango 这本书,必须添加一个 slug 来更新类别 table。但是,我在尝试迁移数据库后遇到错误。
http://www.tangowithdjango.com/book17/chapters/models_templates.html#creating-a-details-page
我没有为 slug 提供默认值,所以 Django 要求我提供一个默认值,并且按照书上的说明我输入了 ''。
值得注意的是,我没有像原书中那样使用 sqlite,而是使用 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'")
您的 table 中的行必须已经带有空 slug,这违反了您创建的 mysql 唯一约束。您可以通过 运行ning manage.py dbshell
手动更新它们以到达 mysql 客户端,然后更新有问题的行,例如
update table rango_category set slug = name where slug = '';
(假设带有空白 slug 的行有名称)。或者您可以使用
删除行delete from rango_category where slug = '';
在那之后,您应该可以 运行 您的迁移。
我们一步一步来分析:
- 您正在添加带有
unique = True
的slug
字段,这意味着:每条记录必须具有不同的值,slug
[= 中不能有两条具有相同值的记录38=] - 您正在创建迁移:django 要求您为数据库中已存在的字段提供默认值,因此您提供了 ''(空字符串)作为该值。
- 现在 django 正在尝试迁移您的数据库。在数据库中我们至少有 2 条记录
- 迁移了第一条记录,slug 列填充了空字符串。这很好,因为没有其他记录在
slug
字段 中有空字符串
- 第二条记录已迁移,slug 列填充有空字符串。那失败了,因为第一条记录在
slug
字段中已经有空字符串。引发异常并中止迁移。
这就是您迁移失败的原因。您应该做的就是编辑迁移,复制 migrations.AlterField
操作两次,在第一次操作中删除 unique=True。在这些操作之间,您应该放置 migrations.RunPython
操作并为其提供 2 个参数:generate_slugs
和 migrations.RunPython.noop
.
现在您必须在迁移之前在迁移函数内部创建 class,将该函数命名为 generate_slugs
。函数应采用 2 个参数:apps
和 schema_editor
。在你的函数放在第一行:
Category = apps.get_model('your_app_name', 'Category')
现在使用 Category.objects.all()
循环所有记录并为每个记录提供唯一的 slug。
如果您的 table 中有多个类别,那么您不能有 unique=True
和 default=''
,因为那样您将有多个类别 slug=''
.如果您的教程要求这样做,那么这是个糟糕的建议,尽管它可能在 SQLite 中有效。
向模型添加唯一字段的正确方法是:
- 删除当前不起作用的迁移。
- 添加 slug 字段,
unique=False
。创建一个新迁移并 运行 它。 - 为每个类别设置一个独特的 slug。听起来 rango 填充脚本可能会这样做。或者,您可以编写一个迁移来设置 slug,甚至可以在 Django 管理中手动设置它们。
- 将 slug 字段更改为
unique=True
。创建一个新迁移并 运行 它。
如果这太难了,那么您可以从数据库中删除除一个类别之外的所有类别。那么您当前的迁移将 运行 而不会出现唯一约束的问题。您可以稍后再次添加类别。