【发布时间】:2021-10-04 13:29:09
【问题描述】:
我有一个模型(我们将其命名为 Material),它最初是在一个单体应用程序中创建的(我们称之为 A)。为了根据业务领域逻辑将这个单体划分为单独的应用程序,我们在一个新应用程序(B)中创建了一个同名的模型,并执行了从 A 到 B 的数据迁移。然后我们从应用程序 A 中删除了模型.
在我们的一个观点中,我们使用依赖于 ContentTypes 的元素过滤器来按应用列出模型的名称,为此,我们使用 ContentType.objects.get_for_models() 和类列表(其中包含 B.Material,但不包含A.Material),但出现错误:
NoneType' object has no attribute '_meta
这是因为 A.Material 类已从代码中消失,但仍存在于 ContentType 表中。当调用get_for_models() 时,似乎是search for combinations of model and app_label 而不是我们提供的列表。里面的filter()结果会有A.Material和B.Material,后来又因为A.Material报错。
虽然我发现 get_for_models() 在这方面的行为很奇怪,但我认为问题在于陈旧的 ContentType。有没有一种安全的方法可以通过 Django 1.11 中的迁移来自动删除 ContentTypes?
我尝试在迁移期间调用.delete(),但迁移后 ContentType 仍然存在。
ContentType = apps.get_model('contenttypes', 'ContentType')
MaterialModel = apps.get_model('my_app', 'Material')
ContentType.objects.get_for_model(MaterialModel).delete()
remove_stale_contenttypes 命令确实检测到它是陈旧的,但我希望在迁移期间完成删除,而不需要其他步骤。
【问题讨论】:
-
你能在迁移过程中分享你的
.delete()吗? -
当然,这是我在迁移中尝试的 ``` ContentType = apps.get_model('contenttypes', 'ContentType') MaterialModel = apps.get_model('my_app', 'Material') ContentType .objects.get_for_model(MaterialModel).delete() ```
-
@AlexandreTaillonDesrochers:请edit整个迁移的问题。
标签: django django-1.11 django-contenttypes