django save another class data while saving a class
from django.db import models
from django.db.models.signals import post_save
from django.dispatch import receiver
class FirstModel(models.Model):
field1 = models.CharField(max_length=255)
field2 = models.IntegerField()
class SecondModel(models.Model):
field3 = models.CharField(max_length=255)
field4 = models.IntegerField()
@receiver(post_save, sender=FirstModel)
def create_second_model(sender, instance, created, kwargs):
if created:
SecondModel.objects.create(field3=instance.field1, field4=instance.field2)
In the code above, we have two Django models, FirstModel
and SecondModel
. The create_second_model
function is a signal receiver that gets triggered after a FirstModel
instance is saved.
- The
FirstModel
has two fields,field1
andfield2
. - The
SecondModel
has two fields,field3
andfield4
. - The
@receiver
decorator is used to connect thecreate_second_model
function to thepost_save
signal of theFirstModel
. This means that the function will be called every time aFirstModel
instance is saved. - In the
create_second_model
function, we check if theFirstModel
instance was just created (created
isTrue
). If it was, we create a newSecondModel
instance using the values offield1
andfield2
from theFirstModel
instance. ```