【问题标题】:Cannot create an instance of a model with GenericForeignKey in migration无法在迁移中创建具有 GenericForeignKey 的模型实例
【发布时间】:2015-03-11 07:34:03
【问题描述】:

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


在 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 实际上并没有保存,我收到@987654328 @

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

【问题讨论】:

  • 你能粘贴模型吗?至少相关位?我在尝试创建一个作为 M2M 领域目标的简单模型时遇到了同样的情况。模型本身没有关系字段。

标签: django django-1.7 django-migrations


【解决方案1】:

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

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

它以某种特殊的方式加载Comment 模型,因此泛型关系等某些功能不起作用。

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

from django_comments import Comment

【讨论】:

  • 不幸的是,这甚至不是一个解决方案。在您将字段添加到评论之前,它一直有效;在迁移过程中,最新模型为模式版本生成 SQL,该版本将在以后的迁移中应用。因此,任何拥有旧数据库的长期项目都不能再应用 ir 迁移
猜你喜欢
  • 2016-12-01
  • 2010-11-13
  • 1970-01-01
  • 1970-01-01
  • 2011-12-20
  • 2015-05-25
  • 2021-05-21
  • 2014-07-10
  • 2022-01-15
相关资源
最近更新 更多