2

I have an Order and Notification Model, whenever there is a new order model instance, i want to immediately create a notification for the new order, i wrote some functions in the models but when there is a new order, the notification instance does not get created. i still think there should be a better way to do this, how can i go about this?

models.py


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



class Notification(models.Model):
    provider = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, related_name="provider_notifications")
    service = models.ForeignKey(Service, on_delete=models.SET_NULL, null=True, related_name="service_notifications")
    order = models.ForeignKey(Orders, on_delete=models.SET_NULL, null=True, related_name="service_order")
    notification_type = models.CharField(max_length=100, choices=NOTIFICATION_TYPE, default="none")
1
  • Where are u calling the create_notification function? Commented Feb 11, 2023 at 4:47

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.