2015-01-13 38 views
5

重要提示:此问题已不再适用。无法在迁移中使用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_typeobject_pk领域。因此,他们content_type实际上并没有保存,我收到django.db.utils.IntegrityError: null value in column "content_type_id" violates not-null constraint

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

+0

你可以粘贴模式?至少有关位? 我遇到了相同的情况,试图创建一个简单的模型,这是M2M领域的目标。模型本身没有关系领域。 – tutuca

回答

3

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

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

它加载在一些特殊的方式Comment模型加载你的模型,所以像一般的关系中的一些功能不起作用。

有一点哈克解决方法:将模型像往常一样:

from django_comments import Comment 
+2

不幸的是,这甚至不是一个解决方案。它的工作原理,直到你添加一个字段评论;在迁移期间,最新日期模型会生成将在稍后迁移中应用的模式版本的SQL。因此,任何具有较旧数据库的长期项目都不能再应用迁移 – rgammans