gpt4 book ai didi

python - Django 重命名模型。创建新的 django_content_type 而不是重命名旧记录

转载 作者:太空宇宙 更新时间:2023-11-03 18:00:20 28 4
gpt4 key购买 nike

设置:

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 关联并保存:

TestGeneric.objects.create(content_object=Building.objects.first())

现在,我将 Buildings 重命名为 Building 并运行 makemigrations。系统提示我 Did you rename the app.Buildings model to Building? [是/否]

我选择是。然后我运行 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 行都不会被吹走?

最佳答案

我刚刚在一个项目中使用了这个;需要注意的是,如果您在尝试应用自动创建的模型重命名迁移之前创建迁移,则此操作不会出现问题。

您需要更改应用名称、型号名称和之前的迁移以匹配您的设置;在此示例中,我们将模型的名称从 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)
]

关于python - Django 重命名模型。创建新的 django_content_type 而不是重命名旧记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27773849/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com