NeoVe
NeoVe

Reputation: 3897

Save related child model fields from parent - Django

I have these models:

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)

What I need, is when I save a record from MyModel1, create automatically an object on MyModel2, MyModel3 and MyModel4. With some filled fields with data from the parent.

So far, I have this:

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')

But when I try to save from parent it throws me:

name 'field2' is not defined

This method is at the end of the parent model, unindented, if I indent it, it throws:

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

If I enclose the sender model (MyModel1) between '' like:

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

It throws:

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

Any ideas?

Upvotes: 0

Views: 417

Answers (1)

albar
albar

Reputation: 3100

The error message is explicit enough. Have you tried this:

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

Also the function create_child_records contains many errors: wrong field names, undefined variables.

Upvotes: 2

Related Questions