代码之家  ›  专栏  ›  技术社区  ›  x-yuri

如何使用Django重命名模型?

  •  5
  • x-yuri  · 技术社区  · 8 年前

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

    我想把它重命名为 Bar .我应该采取什么步骤?我该怎么处理 The following content types are stale

    2 回复  |  直到 8 年前
        1
  •  4
  •   judy    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'),
        ]
    

    再一次

        2
  •  3
  •   x-yuri    8 年前

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

    1. ./manage.py makemigrations
    2. 检查您的数据库中是否有应用程序自己的表中的引用。普通参考和 references via django_content_type table
    3. 检查数据库中是否有来自Django表的引用。很可能是:

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

      就我而言,我在 django_admin_log , auth_group_permissions , auth_user_user_permissions

    4. ./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:
      

      你可以回答 yes foo 上述三个表中的表。或者如果失去他们不是你的问题。

    推荐文章