从父级保存相关子级模型字段-Django

时间:2019-03-20 21:57:58

标签: django python-3.x

我有以下模型:

class MyModel1(models.Model):
    field1 = models.CharField(max_length=128, blank=True, null=True)
    fieldrelated1 = models.OneToOneField('MyModel2', max_length=128, blank=True, null=True, related_name='mymodel2')
    fieldrelated2 = models.OneToOneField('MyModel3', max_length=128, blank=True, null=True, related_name='mymodel3')
    fieldrelated3 = models.OneToOneField('MyModel4', max_length=128, blank=True, null=True, related_name='mymodel4')

class MyModel2(models.Model):
    field2 = models.CharField(max_length=128, blank=True, null=True)
    test = models.CharField(max_length=128, blank=True, null=True)

class MyModel3(models.Model):
    field3 = models.CharField(max_length=128, blank=True, null=True)
    test = models.CharField(max_length=128, blank=True, null=True)

class MyModel4(models.Model):
    field4 = models.CharField(max_length=128, blank=True, null=True)
    test = models.CharField(max_length=128, blank=True, null=True)

我需要的是,当我从MyModel1保存记录时,在MyModel2, MyModel3 and MyModel4上自动创建一个对象。在某些字段中填充了来自父级的数据。

到目前为止,我有这个:

def create_child_records(instance, created, rad, **kwargs):
    if not created or rad:
        return

    if not instance.fieldrelated1_id:
        fieldrelated1, _ = MyModel2.objects.get_or_create(field1=field2)
    instance.fieldrelated1 = fieldrelated1

    if not instance.fieldrelated2_id:
        fieldrelated2, _ = MyModel3.objects.get_or_create(field1=field3)
    instance.fieldrelated2 = fieldrelated2

    if not instance.fieldrelated3_id:
        fieldrelated3, _ = MyModel4.objects.get_or_create(field1=field4)
    instance.fieldrelated3 = fieldrelated3

    instance.save()

models.signals.post_save.connect(create_child_records, sender=MyModel1, dispatch_uid='create_child_records')

但是当我尝试从父母那里保存时,它会抛出我:

name 'field2' is not defined

此方法在父模型的末尾,不缩进,如果我缩进,它会抛出:

ValueError: Invalid model reference MyModel1. String model references must be of the form 'app_label.ModelName'

如果我将发送方模型(MyModel1)放在''之间,例如:

models.signals.post_save.connect(create_child_records, sender='MyModel1', dispatch_uid='create_child_records')

它抛出:

ValueError: Invalid model reference 'MyModel1'. String model references must be of the form 'app_label.ModelName'.

有什么想法吗?

1 个答案:

答案 0 :(得分:2)

该错误消息足够明显。您是否尝试过:

models.signals.post_save.connect(create_child_records, sender='myapp.MyModel1', dispatch_uid='create_child_records')

函数create_child_records还包含许多错误:错误的字段名称,未定义的变量。