[Answered ]-Django – how to automatically create a new model instance when another model instance is created

1πŸ‘

βœ…

You need to do something like the following:

class Orders(models.Model):
    service = models.ForeignKey(Service, on_delete=models.SET_NULL, null=True, related_name="service_orders")
    seller = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, related_name="seller")

    def create_notification(self):
        create_notification = Notification.objects.create(
            provider=self.seller, service=self.service, order=self , notification_type='new_order')
        create_notification.save()
        return create_notification

    def save(self, force_insert=False, force_update=False, using=None, update_fields=None):
        super().save(force_insert=force_insert, force_update=force_update, using=using, update_fields=update_fields)
        self.create_notification()

Where save method will be overwriten and once you persist it in the database layer then you can safety call the method create_notification.

Best way to achieve it could be using signals to decouple the logic from the model and manage it in a separate business logic component, but if you don’t mind applying the best practices you are good to go with the solution.

πŸ‘€allexiusw

Leave a comment