Consider the following code, in which I have one parent, and all the child models related to the parent by ForeignKey
relationship. Each child may have their own child, making the whole family look like a tree structure.
class Parent(models.Model):
field = models.CharField(max_length=100, primary_key=True)
class Child_1(models.Model):
parent = models.ForeignKey(Parent, models.CASCADE, related_name='aa')
class Child_2(models.Model):
parent = models.ForeignKey(Parent, models.CASCADE, related_name='aa')
class Child_1_Child_1(models.Model):
parent = models.ForeignKey(Child_1, models.CASCADE, related_name='aa')
class Child_1_Child_2(models.Model):
parent = models.ForeignKey(Child_1, models.CASCADE, related_name='aa')
Upon making an object for Parent
, I want to create all the child objects.
I guess I can create all the child objects like this:
parent = Parent.objects.create(**kwargs)
child_1 = Child_1.objects.create(parent=parent)
child_2 = Child_2.objects.create(parent=parent)
child_1_child_1 = Child_1_Child_1.objects.create(parent=child_1)
child_1_child_2 = Child_1_Child_2.objects.create(parent=child_1)
...
But you know, this doesn't look very good. Is there any built-in Django method that handles this kind of parent-child object creation in chain?