Django重命名模型。创建新的Django_content_类型,而不是重命名旧记录

2024-09-29 22:27:48 发布

您现在位置:Python中文网/ 问答频道 /正文

设置:

Django 1.7 | Postgres 9.x版

class Buildings(BaseModel):
    number = models.CharField(max_length=25)

class TestGeneric(models.Model):

    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField()
    content_object = GenericForeignKey()

假设我创建了一个TestGeneric实例,将其与Building关联并保存了它:

^{pr2}$

现在我将Buildings重命名为Building,然后运行makemigrations。我被提示Did you rename the app.Buildings model to Building? [y/N]

我选择是的。然后我运行migrate,得到:

The following content types are stale and need to be deleted:

app | buildings

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'.

不管我回答什么,Django将自动在django_content_type中创建一个新行,名称和标签为building。有没有办法只重命名ContentType,这样我所有的TestGeneric行都不会被吹走?在


Tags: todjangoyouappobjectmodelstypecontent
1条回答
网友
1楼 · 发布于 2024-09-29 22:27:48

我刚刚在一个项目中使用了这个方法;警告是,如果您在尝试应用自动创建的模型重命名迁移之前创建了迁移,那么这个方法是可以正常工作的。在

您需要更改应用程序名称、模型名称和以前的迁移以匹配您的设置;在本例中,我们将模型的名称从profile更改为member。在

# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import migrations
from django.conf import settings

sql = """UPDATE django_content_type
         SET name = 'member',
             model = 'member'
         WHERE name = 'profile' AND
               model = 'profile' AND
               app_label = 'open_humans';"""

reverse_sql = """UPDATE django_content_type
                 SET name = 'profile',
                     model = 'profile'
                 WHERE name = 'member' AND
                       model = 'member' AND
                       app_label = 'open_humans';"""


class Migration(migrations.Migration):

    dependencies = [
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
        ('open_humans', '0004_auto_20150106_1828'),
    ]

    operations = [
        migrations.RunSQL(sql, reverse_sql)
    ]

相关问题 更多 >

    热门问题