首页 > 解决方案 > 重命名在另一个模型中用作超类的模型

问题描述

我有一个FirstName需要重命名为的SecondName类,但该类也用作其他模型的基类。

# file 1
class FirstName(models.Model):
    pass # stuff


# file 2
from firstfile.models import FirstName

class ProxyModel(FirstName):
    pass # stuff

我尝试更新模型名称以及对它的所有引用...

# file 1
class SecondName(models.Model):
    pass # stuff


# file 2
from firstfile.models import SecondName

class ProxyModel(SecondName):
    pass # stuff


# migration
operations = [
    migrations.RenameModel(
        old_name='FirstName',
        new_name='SecondName',
    ),
]

但是当我运行makemigrations或“迁移”时出现错误:

django.db.migrations.exceptions.InvalidBasesError: Cannot resolve
bases for [<ModelState:
'my_app.ProxyModel'>] This can happen if you are
inheriting models from an app with migrations (e.g. contrib.auth)  in
an app with no migrations;

似乎我无法在迁移之前导入重命名的基本模型,但在解决基类问题之前我无法迁移......

我已经尝试使用以前的模型名称作为 Proxy 基类,但得到模型未找到错误。我还尝试注释掉代理模型,但仍然出现错误(我认为是因为该代理模型已经运行了迁移)。

我怎样才能绕过这个重命名依赖循环?

Python 2.7、Django 1.11

标签: pythondjangopython-2.7

解决方案


为什么不使用db_table元属性而不是重命名数据库中的表?

class SecondName(models.Model):
    pass # stuff

    class Meta:
        db_table = 'app_firstname'

推荐阅读