'ContentType' 对象在数据迁移中没有属性 'model_class'
'ContentType' object has no attribute 'model_class' in data migration
我的数据迁移文件中有这个:
def set_target_user(apps, schema_editor):
LogEntry = apps.get_model('auditlog', 'LogEntry')
ContentType = apps.get_model('contenttypes', 'ContentType')
for entry in LogEntry.objects.filter(target_user=None):
ct = ContentType.objects.get(id=entry.content_type.id)
model = ct.model_class()
我提到了 AttributeError。但它在其他模块(不是 migratins)中运行良好。有什么办法可以克服这个问题吗?
当您在迁移中调用 apps.get_model
时,您不会获得实际模型 class,您会得到一个特定于迁移的 class,它是使用存在的字段动态创建的在迁移历史的那个时刻。它不会有任何真正的 ContentType 模型的方法。
您可能应该再次使用 apps.get_model
来获取该内容类型的历史模型:
model = apps.get_model(ct.app_label, ct.model)
我的数据迁移文件中有这个:
def set_target_user(apps, schema_editor):
LogEntry = apps.get_model('auditlog', 'LogEntry')
ContentType = apps.get_model('contenttypes', 'ContentType')
for entry in LogEntry.objects.filter(target_user=None):
ct = ContentType.objects.get(id=entry.content_type.id)
model = ct.model_class()
我提到了 AttributeError。但它在其他模块(不是 migratins)中运行良好。有什么办法可以克服这个问题吗?
当您在迁移中调用 apps.get_model
时,您不会获得实际模型 class,您会得到一个特定于迁移的 class,它是使用存在的字段动态创建的在迁移历史的那个时刻。它不会有任何真正的 ContentType 模型的方法。
您可能应该再次使用 apps.get_model
来获取该内容类型的历史模型:
model = apps.get_model(ct.app_label, ct.model)