我正在尝试关注tangowithdjango书,必须添加一个slug来更新类别表。但是,我在尝试迁移数据库后遇到错误。
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'")
答案 0 :(得分:9)
让我们一步一步地分析它:
slug
添加unique = True
字段,这意味着:每条记录必须具有不同的值,slug
slug
字段slug
字段中已经有空字符串。提出异常并中止迁移。这就是您的迁移失败的原因。您应该做的就是编辑迁移,复制migrations.AlterField
操作两次,在第一次操作中删除unique = True。在这些操作之间,您应该执行migrations.RunPython
操作,并在其中提供2个参数:generate_slugs
和migrations.RunPython.noop
。
现在,您必须在迁移功能之前创建迁移功能,并将该功能命名为generate_slugs
。函数应该有两个参数:apps
和schema_editor
。在你的函数放在第一行:
Category = apps.get_model('your_app_name', 'Category')
现在使用Category.objects.all()
循环所有记录并为每个记录提供唯一的slug。
答案 1 :(得分:2)
如果您的表格中有多个类别,则表示您不能拥有unique=True
和default=''
,因为这样您将拥有多个slug=''
类别。如果你的教程说要做到这一点,那么这是一个糟糕的建议,尽管它可能在SQLite中有用。
向模型添加唯一字段的正确方法是:
unique=False
添加slug字段。创建一个新的迁移并运行它。unique=True
。创建一个新的迁移并运行它。如果这太难了,那么你可以从数据库中删除所有类别,除了一个。然后,您的当前迁移将在没有唯一约束问题的情况下运行。您可以在之后再次添加类别。
答案 2 :(得分:1)
您的表中必须有空行的行,这违反了您创建的mysql唯一约束。您可以通过运行manage.py dbshell
来手动更新它们以进入mysql客户端,然后更新有问题的行,例如
update table rango_category set slug = name where slug = '';
(假设具有空白slugs的行具有名称)。或者您可以使用
删除行 delete from rango_category where slug = '';
之后,您应该能够运行迁移。