How to populate Model B when saving Model A

I have two Model, A and B respectively. I have created an modelform for Model A which i use in creating instances of Model A. What i want to achieve is that whenever i save Model A, i want an instance of Model B to be created automatically.

class A(models.Model):
    member = models.ForeignKey(User, on_delete=models.CASCADE, default="")
    book = models.ForeignKey(Books, on_delete=models.CASCADE, default="")
    library_no = models.CharField(default="", max_length=255, blank=True)
    staff_id = models.CharField(default="", max_length=255, blank=True)
    application_date = models.DateTimeField(auto_now_add=True)

    class Meta:
        verbose_name_plural = " Borrow Book"

    def __str__(self):
        return (str(self.member)) + " " + "applied to borrow " + (str(

class B(models.Model):
    application = models.ForeignKey(BorrowBook, on_delete=models.SET_NULL, default="", null=True)
    approved = models.BooleanField()
    approval_date = models.DateTimeField(auto_now_add=True)

    class Meta:
        verbose_name_plural = "Approved Lending"

    def __str__(self):
        return str(self.application)

Any idea as to how i can achieve it.

You can use signals(post_save) to achieve this, create a file(as django docs recommends) and import the following:

from django.db.models.signals import post_save
from django.dispatch import receiver

# then write the function to implement it

@receiver(post_save, sender=A)
def create_b_instance(sender, instance, created, **kwargs):
    if created:
        B.objects.create(...) # do functionality here

Now here whenever the sender (A) is created the function inside def create_b_instance is worked.

Refer this doc for more details.

Back to Top