Cha*_*ntz 7 django data-migration instantiation django-south generic-foreign-key
我需要在应用程序问题中执行模型答案的数据迁移.在该脚本中存在依赖性,因此我需要创建应用程序日记中的模型章的实例.所以,我把它编码如下:
def forwards(self, orm):
for answer_object in orm.Answer.objects.all():
#This Works.
blog, is_created = orm['blog.Post'].objects.get_or_create(title=answer_object.answer[:100])
blog.save()
#This DOES NOT work
chapter, is_created = orm['journal.Chapter'].objects.get_or_create(content_object=blog)
chapter.save()
#cleanup task, not relevant to this question below
answer_object.chapter_ptr = chapter
answer_object.save()
Run Code Online (Sandbox Code Playgroud)
但正如预期的那样,这会在"orm ['journal.Chapter']上引发错误.objects.get_or_create(content_object = blog)"
django.core.exceptions.FieldError: Cannot resolve keyword 'content_object' into field.
Run Code Online (Sandbox Code Playgroud)
这可能是由于content_object是GenericForeignKey,因此不允许进行某些操作.但我也尝试了其他替代方法来创建"章节"对象,比如
chapter = orm['journal.Chapter'](content_object=blog)
ERROR > TypeError: 'content_object' is an invalid keyword argument for this function
Run Code Online (Sandbox Code Playgroud)
和
chapter = orm.journal.Chapter(content_object=blog)
ERROR > AttributeError: The model 'journal' from the app 'questions' is not available in this migration. (Did you use orm.ModelName, not orm['app.ModelName']?)
Run Code Online (Sandbox Code Playgroud)
那我哪里错了?任何指针赞赏.谢谢.
UPDATE
所以,由于我早期的方法失败,我尝试了一个新的方法.其实例化时没有在我的代码模型上面,即第一章在杂志应用程序,我决定,而不是创建一个datamigration.我还确定--freeze了我在forwards定义中提到的模型.我想,这应该是直截了当的.我的正向代码如下 -
def forwards(self, orm):
for answer_object in orm['questions.Answer'].objects.all():
#Works, AGAIN!
blog, is_created = orm['blog.Post'].objects.get_or_create(title=answer_object.answer[:100])
blog.save()
# DOES NOT WORK, AGAIN!
chapter = orm.Chapter(rank=1, content_object=blog)
chapter.save()
Run Code Online (Sandbox Code Playgroud)
我会想到,既然我正在创建一个模型(章节)的实例,它存在于主题应用程序(Journal)中,一切都应该已经解决了.但我得到了同样的错误.
TypeError: 'content_object' is an invalid keyword argument for this function
Run Code Online (Sandbox Code Playgroud)
它在同一点失败,即"content_object".如果可能有帮助,我会在模型定义下面发布.
class Chapter(models.Model):
rank = models.IntegerField()
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
content_object = generic.GenericForeignKey()
Run Code Online (Sandbox Code Playgroud)
更新2 想要在这些转发方法中添加所有被触及的模型,即 - 博客,章节,问题; 在South的schemamigration创建的00n _*.py文件中完全定义.
在获得Rob和南方和Django用户组的帮助后,我能够解决这个问题.以下是我的forwardsdatamigration脚本的定义.
def forwards(self, orm):
for answer_object in orm['questions.Answer'].objects.all():
blog, is_created = orm['blog.Post'].objects.get_or_create(title=answer_object.answer[:100])
blog.save()
#I have to manually lookup the content_type ans set it in the chapter creation.
ct = orm['contenttypes.ContentType'].objects.get(app_label="blog", model="post")
chapter = orm.Chapter(rank=1, content_type=ct, object_id=blog.id)
chapter.save()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3415 次 |
| 最近记录: |