Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

In Django, one way to add data to a child table after the creation of the corresponding parent record is to use signals.

  1. Define a signal receiver function that handles the post-save signal of the parent model. This function will receive the parent instance as an argument.

  2. In the receiver function, create the child instances using the parent instance and any other required data.

  3. Save the child instances.

Here is an example:

from django.db.models.signals import post_save
from django.dispatch import receiver
from myapp.models import ParentModel, ChildModel

@receiver(post_save, sender=ParentModel)
def create_child_records(sender, instance, created, **kwargs):
    if created:
        for i in range(3):
            ChildModel.objects.create(
                parent=instance,
                field1='value1',
                field2='value2'
            )

In this example, the create_child_records function will be called every time a new ParentModel instance is saved. It creates three ChildModel instances with the parent field set to the parent instance and the field1 and field2 values set to 'value1' and 'value2', respectively.