django admin在重命名的字段上引用FieldDoesNotExist

时间:2016-12-28 13:00:30

标签: django django-models django-admin django-migrations

抱歉新手问题,但我无法理解为什么会发生这种情况以及如何解决它。 我创建了评论模型

class Migration(migrations.Migration):

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

operations = [
    migrations.CreateModel(
        name='Comment',
        fields=[
            ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
            ('text', models.TextField()),
            ('pub_date', models.DateTimeField(default=django.utils.timezone.now, verbose_name='date published')),
            ('lft', models.PositiveIntegerField(db_index=True, editable=False)),
            ('rght', models.PositiveIntegerField(db_index=True, editable=False)),
            ('tree_id', models.PositiveIntegerField(db_index=True, editable=False)),
            ('level', models.PositiveIntegerField(db_index=True, editable=False)),
            ('parent', mptt.fields.TreeForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='children', to='myblog.Comment')),
        ],
        options={
            'abstract': False,
        },
    ),
]

之后我意识到我忘记了FK的文章。

class Comment(MPTTModel):
    text = models.TextField()
    parent_article = models.ForeignKey(Article, on_delete=models.CASCADE)
    parent_comment = TreeForeignKey('self', null=True, blank=True, related_name='children', db_index=True)
    pub_date = models.DateTimeField('date published', default=timezone.now)

    class MPTTMeta:
        order_insertion_by = ['pub_date']


class Migration(migrations.Migration):

dependencies = [
    ('myblog', '0002_comment'),
]

operations = [
    migrations.RenameField(
        model_name='comment',
        old_name='parent',
        new_name='parent_comment',
    ),
    migrations.AddField(
        model_name='comment',
        name='parent_article',
        field=models.ForeignKey(default=0, on_delete=django.db.models.deletion.CASCADE, to='myblog.Article'),
        preserve_default=False,
    ),
]

现在我无法在管理网站上添加评论,因为它有效。

 FieldDoesNotExist at /admin/myblog/comment/add/
 Comment has no field named 'parent'

我该如何解决?我是否必须删除评论模型并从开始?

开始

我知道我改名为FK,但django没有。管理员如何获取字段列表?从迁移,而不是从模型?

谢谢。

1 个答案:

答案 0 :(得分:1)

这是因为在添加外键时,您也重命名了它!

migrations.RenameField(
    model_name='comment',
    old_name='parent',
    new_name='parent_comment',
),

现在,该字段被称为parent_comment,要么回滚迁移,要么使用新字段名称。也可以将parent_comment重命名为parent!