重要提示:此问题不再相关。
<小时/>在 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),
]
它会产生一个错误:
类型错误:“content_object”是此函数的无效关键字参数
但是,相同的代码(即 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"违反了非空约束
知道如何在迁移中正确创建具有通用外键的模型吗?或者有什么解决办法吗?
最佳答案
这是迁移模型加载器的问题。您使用默认加载模型
Comment = apps.get_model('django_comments', 'Comment')
它以某种特殊的方式加载Comment
模型,因此一些功能(例如通用关系)不起作用。
有一个有点 hacky 的解决方案:照常加载模型:
from django_comments import Comment
关于django - 无法在迁移中使用 GenericForeignKey 创建模型实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27920556/