重要提示:这个问题不再相关。
在 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
知道如何在迁移中正确创建具有通用外键的模型吗?或者任何解决方法?