如何使用Django重命名模型?

7
假设我有以下这个模型:
class Foo(models.Model):
    name = models.CharField(max_length=255)

我想将它重命名为Bar。我需要采取哪些步骤?如何处理The following content types are stale提示?


你不能只是重命名它并运行 ./manage.py makemigrations 吗? - C14L
@C14L 为此,您必须具备一些 Django 内部知识。请参阅我的答案。 - x-yuri
2个回答

7

小提示:

在一些情况下,当您更改一个模型的名称并运行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


3
我相信,当您需要重命名一个模型时,您只需要重命名类。然后运行 makemigrations。然后处理其他事项。这可以让工作流程更简单。特别是,您将避免遇到像这样的问题。 - x-yuri
2
你仍然需要检查迁移文件,如果它将其解释为删除并创建新模型,则注释掉这些行,并在此答案中添加操作列表。 - Patrick Mutuku

5
在我的特定情况下,情况是这样的:
  1. Rename model class name and all its references.
  2. Run ./manage.py makemigrations.
  3. Inspect your database for references from tables your apps own. Ordinary references and references via django_content_type table. Deal with them accordingly.
  4. Inspect your database for references from Django tables. Most likely that would be:

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

    In my case I had no records in django_admin_log, auth_group_permissions, auth_user_user_permissions.

  5. Run ./manage.py migrate. When it asks:

    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:
    

    You can answer yes only if you have no records referencing records in foo table in the three tables mentioned above. Or if losing them is not an issue for you.


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