5

重要提示:这个问题不再相关。


在 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_typeobject_pk字段,它们content_type实际上并没有保存,我收到了django.db.utils.IntegrityError: null value in column "content_type_id" violates not-null constraint

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

4

1 回答 1

3

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

Comment = apps.get_model('django_comments', 'Comment')

它以某种特殊的方式加载Comment模型,因此诸如通用关系之类的某些功能不起作用。

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

from django_comments import Comment
于 2015-03-03T13:14:52.693 回答