Django迁移后出现AttributeError: 'CharField' object has no attribute 'model'

4
注意:我正在使用Django 1.9和Python 3.4.2
当我更改模型并执行迁移(./manage.py makemigrations),然后尝试应用该迁移(./manage.py migrate)时,我遇到了一个奇怪的错误。
类似的问题在这里有一个链接,但是没有答案,人们询问更多信息,评论中唯一可能的解决方案似乎是删除迁移文件并重新开始 - 但我真的很想知道是什么导致了这个问题以及如何正确地解决它。
错误信息如下:
Operations to perform:
  Apply all migrations: contenttypes, admin, auth, blog, sessions
Running migrations:
  Rendering model states... DONE
  Applying blog.0004_auto_20160103_1321...Traceback (most recent call last):
  File "./manage.py", line 10, in <module>
    execute_from_command_line(sys.argv)
  File "/Users/owen/src/projects/owen/lib/python3.4/site-packages/django/core/management/__init__.py", line 350, in execute_from_command_line
    utility.execute()
  File "/Users/owen/src/projects/owen/lib/python3.4/site-packages/django/core/management/__init__.py", line 342, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/Users/owen/src/projects/owen/lib/python3.4/site-packages/django/core/management/base.py", line 348, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/Users/owen/src/projects/owen/lib/python3.4/site-packages/django/core/management/base.py", line 399, in execute
    output = self.handle(*args, **options)
  File "/Users/owen/src/projects/owen/lib/python3.4/site-packages/django/core/management/commands/migrate.py", line 200, in handle
    executor.migrate(targets, plan, fake=fake, fake_initial=fake_initial)
  File "/Users/owen/src/projects/owen/lib/python3.4/site-packages/django/db/migrations/executor.py", line 92, in migrate
    self._migrate_all_forwards(plan, full_plan, fake=fake, fake_initial=fake_initial)
  File "/Users/owen/src/projects/owen/lib/python3.4/site-packages/django/db/migrations/executor.py", line 121, in _migrate_all_forwards
    state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial)
  File "/Users/owen/src/projects/owen/lib/python3.4/site-packages/django/db/migrations/executor.py", line 198, in apply_migration
    state = migration.apply(state, schema_editor)
  File "/Users/owen/src/projects/owen/lib/python3.4/site-packages/django/db/migrations/migration.py", line 123, in apply
    operation.database_forwards(self.app_label, schema_editor, old_state, project_state)
  File "/Users/owen/src/projects/owen/lib/python3.4/site-packages/django/db/migrations/operations/fields.py", line 201, in database_forwards
    schema_editor.alter_field(from_model, from_field, to_field)
  File "/Users/owen/src/projects/owen/lib/python3.4/site-packages/django/db/backends/base/schema.py", line 482, in alter_field
    old_db_params, new_db_params, strict)
  File "/Users/owen/src/projects/owen/lib/python3.4/site-packages/django/db/backends/base/schema.py", line 564, in _alter_field
    old_default = self.effective_default(old_field)
  File "/Users/owen/src/projects/owen/lib/python3.4/site-packages/django/db/backends/base/schema.py", line 210, in effective_default
    default = field.get_db_prep_save(default, self.connection)
  File "/Users/owen/src/projects/owen/lib/python3.4/site-packages/django/db/models/fields/__init__.py", line 728, in get_db_prep_save
    prepared=False)
  File "/Users/owen/src/projects/owen/lib/python3.4/site-packages/django/db/models/fields/__init__.py", line 720, in get_db_prep_value
    value = self.get_prep_value(value)
  File "/Users/owen/src/projects/owen/lib/python3.4/site-packages/django/db/models/fields/__init__.py", line 1112, in get_prep_value
    return self.to_python(value)
  File "/Users/owen/src/projects/owen/lib/python3.4/site-packages/django/db/models/fields/__init__.py", line 1108, in to_python
    return smart_text(value)
  File "/Users/owen/src/projects/owen/lib/python3.4/site-packages/django/utils/encoding.py", line 42, in smart_text
    return force_text(s, encoding, strings_only, errors)
  File "/Users/owen/src/projects/owen/lib/python3.4/site-packages/django/utils/encoding.py", line 76, in force_text
    s = six.text_type(s)
  File "/Users/owen/src/projects/owen/lib/python3.4/site-packages/django/db/models/fields/__init__.py", line 188, in __str__
    model = self.model
AttributeError: 'CharField' object has no attribute 'model'

变更前的模型:

from django.db import models
from django.utils import timezone


class Category(models.Model):
    title = models.CharField(max_length=100, unique=True)

    def __str__(self):
        return self.title

    def number_of_articles(self):
        articles = Article.objects.filter(categories__pk=self.id)
        return articles.count()


class Article(models.Model):
    title = models.CharField(max_length=255, unique=True)
    slug = models.SlugField(max_length=255, unique=True, default=title)
    pub_date = models.DateTimeField('date published', default=timezone.now)
    intro_text = models.TextField(blank=True)
    body_copy = models.TextField(blank=False)
    votes_helpful = models.IntegerField(default=0, blank=True)
    votes_unhelpful = models.IntegerField(default=0, blank=True)

    categories = models.ManyToManyField(Category, blank=True)

    class Meta:
        ordering = ('-pub_date',)

    def __str__(self):
        return self.title

    def has_votes(self):
        total_num_votes = self.votes_helpful + self.votes_unhelpful
        return total_num_votes > 0

我的模型变更:

slug = models.SlugField(max_length=255, blank=True)

修改的地方是我从 Article 中删除了 unique=True, default=title,并添加了 blank=False

我的迁移文件:

# -*- coding: utf-8 -*-
# Generated by Django 1.9 on 2016-01-03 13:21
from __future__ import unicode_literals

from django.db import migrations, models


class Migration(migrations.Migration):

    dependencies = [
        ('blog', '0003_auto_20151230_1643'),
    ]

    operations = [
        migrations.AlterField(
            model_name='article',
            name='slug',
            field=models.SlugField(blank=True, max_length=255),
        ),
    ]

这很奇怪,因为原始代码是无效的:你不能像这样引用另一个字段作为默认值。所以我不确定这个怎么可能运行过。 - Daniel Roseman
是的,我也不明白,出于某种原因,它一直在工作,直到现在。 - shrewdbeans
1个回答

5
slug = models.SlugField(max_length=255, unique=True, default=title)

这将把你的slug字段的默认值设置为CharField实例。这是不正确的,我很惊讶之前没有给你报错。
我认为唯一的解决办法是更改引入旧默认值的迁移文件,并将默认值更改为有效值。

1
我已更改了我的初始迁移文件(0001_initial.py)并将默认值从 CharField 更改为 None,代码如下: ('slug', models.SlugField(default=None, max_length=255, unique=True))。这样做有效了!现在我的迁移没有出现错误。谢谢您。 - shrewdbeans
谢谢...我之前也被同样的错误信息困扰过,这个指出了基本上相同的原因:一个CharField默认设置为一个CharField实例。 - mmw

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