【问题标题】:Rename Model that is used as a superclass in another model重命名在另一个模型中用作超类的模型
【发布时间】:2019-11-18 17:21:56
【问题描述】:

我有一个类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

【问题讨论】:

    标签: python django python-2.7


    【解决方案1】:

    与其重命名数据库中的表,不如使用db_table元属性?

    class SecondName(models.Model):
        pass # stuff
    
        class Meta:
            db_table = 'app_firstname'
    

    【讨论】:

    • 在这种情况下,您是否要创建一个新类 SecondName 并将其映射到 FirstName 表?我们确实希望子类继承自新的类名 SecondName。
    猜你喜欢
    • 2014-11-18
    • 2015-11-07
    • 1970-01-01
    • 2012-12-02
    • 2021-08-11
    • 2019-05-25
    • 2012-02-27
    • 2022-01-15
    • 2018-09-21
    相关资源
    最近更新 更多