无法在迁移中使用GenericForeignKey创建模型实例

时间:2015-01-13 10:59:16

标签: django django-1.7 django-migrations

重要提示:此问题已不再适用。


在Django 1.7迁移中,我尝试使用以下代码以编程方式创建Comment条目:

# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations

class Migration(migrations.Migration):

    def create_genericcomment_from_bookingcomment(apps, schema_editor):

        BookingComment = apps.get_model('booking', 'BookingComment')
        Comment = apps.get_model('django_comments', 'Comment')
        for comment in BookingComment.objects.all():
            new = Comment(content_object=comment.booking)
            new.save()

    dependencies = [
        ('comments', '0001_initial'),
        ('django_comments', '__first__'),
    ]

    operations = [
        migrations.RunPython(create_genericcomment_from_bookingcomment),
    ]

它会产生错误: TypeError: 'content_object' is an invalid keyword argument for this function

但是,相同的代码(即Comment(content_object=comment.booking))在shell中执行时可以正常工作。

我尝试使用new = Comment()创建一个空白模型,然后手动设置所有必填字段,但即使我相应地设置了content_typeobject_pk字段,它们content_type也是实际上没有保存,我收到django.db.utils.IntegrityError: null value in column "content_type_id" violates not-null constraint

知道如何在迁移中正确创建具有通用外键的模型吗?或者任何解决方法?

1 个答案:

答案 0 :(得分:3)

这是迁移模型加载器的问题。您使用默认

加载模型
Comment = apps.get_model('django_comments', 'Comment')

它以某种特殊方式加载Comment模型,因此某些功能(如泛型关系)不起作用。

有一点hacky解决方案:像往常一样加载你的模型:

from django_comments import Comment
相关问题