【发布时间】: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_type 和object_pk 字段,它们content_type 实际上并没有保存,我收到@987654328 @
知道如何在迁移中正确创建具有通用外键的模型吗?或者有什么解决方法?
【问题讨论】:
-
你能粘贴模型吗?至少相关位?我在尝试创建一个作为 M2M 领域目标的简单模型时遇到了同样的情况。模型本身没有关系字段。
标签: django django-1.7 django-migrations