Ask Your Question
2

How can data be added to a child table after the creation of the corresponding parent record in Django?

asked 2022-06-01 11:00:00 +0000

nofretete gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2022-04-15 01:00:00 +0000

plato gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-06-01 11:00:00 +0000

Seen: 8 times

Last updated: Apr 15 '22