【问题标题】:How do I rename a model with Django?如何使用 Django 重命名模型?
【发布时间】:2018-01-20 22:52:26
【问题描述】:

假设我有这个模型:

class Foo(models.Model):
    name = models.CharField(max_length=255)

我想将其重命名为 Bar。我应该采取哪些步骤?以及如何处理The following content types are stale提示符?

【问题讨论】:

  • 你不能重命名它并运行./manage.py makemigrations吗?
  • @C14L 为此,您必须对 Django 内部结构有所了解。看我的回答。

标签: python django rename database-migration table-rename


【解决方案1】:

在我的特殊情况下是这样的:

  1. 重命名模型类名称及其所有引用。
  2. 运行./manage.py makemigrations
  3. 检查您的数据库中是否有来自您的应用程序拥有的表的引用。普通参考和references via django_content_type table。相应地处理它们。
  4. 检查您的数据库是否有来自 Django 表的引用。很可能是:

    my_table-+-django_admin_log
             `-auth_permission-+-auth_group_permissions
                               `-auth_user_user_permissions
    

    就我而言,django_admin_logauth_group_permissionsauth_user_user_permissions 中没有记录。

  5. 运行./manage.py migrate。当它询问时:

    The following content types are stale and need to be deleted:                
    
        myapp | foo
    
    Any objects related to these content types by a foreign key will also         
    be deleted. Are you sure you want to delete these content types?              
    If you're unsure, answer 'no'.                                                  
    
        Type 'yes' to continue, or 'no' to cancel:
    

    只有在上述三个表中没有引用foo 表中记录的记录时,才可以回答yes。或者,如果丢失它们对您来说不是问题。

【讨论】:

    【解决方案2】:

    旁注:

    在某些情况下,当您更改模型名称然后运行 ​​python manage.py makemigrations 时,您会看到自动生成的迁移正在添加新模型,然后删除旧模型(逐个字段,然后是模型本身) .

    如果发生这种情况,那么您在尝试运行 python manage.py migrate 时可能会收到此错误:

    django.db.utils.IntegrityError: (1451, 'Cannot delete or update a parent row: a foreign key constraint fails')
    

    要解决这个问题:打开自动生成的迁移文件并手动编辑它,如下所示:

    operations = [
            migrations.RenameModel('Foo', 'Bar'),
        ]
    

    然后再次运行python manage.py migrate

    【讨论】:

    • 我相信,当您需要重命名模型时,您必须 just rename the class,仅此而已。然后运行makemigrations。然后一切。这使得工作流程更简单。特别是,您不会遇到这样的问题。
    • 您仍然需要检查迁移文件,如果将其解释为删除并创建新模型,请注释掉这些行并在此答案中添加操作列表。
    猜你喜欢
    • 2011-03-15
    • 2011-07-23
    • 2015-11-10
    • 2020-01-10
    • 1970-01-01
    • 2011-01-28
    • 2015-01-26
    • 2021-04-09
    • 2011-10-01
    相关资源
    最近更新 更多