“ ContentType”对象在数据迁移中没有属性“ model_class”

Дми*_*нев 1 django django-migrations

我的数据迁移文件中有此文件:

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()
Run Code Online (Sandbox Code Playgroud)

我提到了AttributeError。但是它在其他模块(不是migratins)中也能很好地工作。任何想法如何克服这个?

Dan*_*man 5

调用apps.get_model迁移时,您没有得到实际的模型类,而是得到了特定于迁移的类,该类是使用迁移历史记录中此时存在的字段动态创建的。它没有真正的ContentType模型的任何方法。

您可能应该apps.get_model再次使用以获得该内容类型的历史模型:

model = apps.get_model(ct.app_label, ct.model)
Run Code Online (Sandbox Code Playgroud)