重要提示:此问题已不再适用。无法在迁移中使用GenericForeignKey创建模型的实例
在Django 1.7迁移我尝试以编程方式创建注释条目下面的代码:
# -*- 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_type
和object_pk
领域。因此,他们content_type
实际上并没有保存,我收到django.db.utils.IntegrityError: null value in column "content_type_id" violates not-null constraint
任何想法如何在迁移中正确创建一个具有通用外键的模型?或者任何解决方法?
你可以粘贴模式?至少有关位? 我遇到了相同的情况,试图创建一个简单的模型,这是M2M领域的目标。模型本身没有关系领域。 – tutuca