简体   繁体   English

在迁移中处理 GenericRelation 和 GenricForeignKey

[英]Dealing GenericRelation and GenricForeignKey inside migrations

I have models with GenricForeigKey and GenericRelation fields.我有带有 GenricForeigKey 和 GenericRelation 字段的模型。

class Datasheet(models.Model):
    package1 = GenericRelation('PackageInstance')
    ...

class PackageInstance(models.Model):
    content_object = GenericForeignKey()
    object_id = models.PositiveIntegerField(null=True)
    content_type = models.ForeignKey(ContentType, null=True, on_delete=models.CASCADE)
    ....

I am migrating from another models, inside my migration I want to create new instance.我正在从另一个模型迁移,在我的迁移中我想创建新实例。

    for ds in Datasheet.objects.all():
        pi = PackageInstance.objects.create(content_object=ds)

However this fails然而这失败了

TypeError: DesignInstance() got an unexpected keyword argument 'content_object'

Additionally, ds.package1.all() will also fail.此外, ds.package1.all()也会失败。

AttributeError: 'Datasheet' object has no attribute 'package1'

How do I solve this?我该如何解决这个问题?

I did some research but did not find a direct answer to my question.我做了一些研究,但没有找到我问题的直接答案。 The most important thing to remember is that model methods will not be available in migrations.要记住的最重要的事情是 model 方法在迁移中不可用。 This includes fields created by the Content Types framework.这包括由内容类型框架创建的字段。 However, object_id and content_type will be there.但是, object_idcontent_type将在那里。

My solution is to simply create things by hand.我的解决方案是简单地手动创建东西。

ContentType = apps.get_model('contenttypes', 'ContentType')

Datasheet = apps.get_model('api', 'Datasheet')
DatasheetContentType = ContentType.objects.get(model=Datasheet._meta.model_name, app_label=Datasheet._meta.app_label)

for ds in Datasheet.objects.all():
    di = DesignInstance.objects.create(object_id=ds.id, content_type=DatasheetContentType)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM