[Answered ]-Django: use related_name to create a subclass

1👍

You’re trying to perform action on NoneType object eg. instance.child
because when you create your Parent instance you’ve to assing child to your Parent.child attribute so by default it will None so to assign child to your Parent class you can do like this & you don’t require signals you can do this inside your save method.

class Parent(models.Model):
    name = models.TextField()
    child = models.ForeignKey(Child, on_delete=models.SET_NULL, related_name="parent_child", null=True, blank=True)

    def save(self, *args, **kwargs):
        if not self.child:
           self.child = Child.objects.create(name="I am a child")
        super(Parent, self).save(*args, **kwargs)

also you’re trying to access related object in wrong way if you’re inside Parent you can access child directly using Parent.child & if you want to access Parent from Child then you can do like this Child.parent_child read more about backward relation

0👍

def post_save_receiver(sender, instance, *args, **kwargs)
    if not instance.child:
        child = Child(name='I am a child').save()
        instance.child = child
        instance.save()

Leave a comment