Home > Mobile >  Django: How to automatically update a model instance everytime another model instance is updated
Django: How to automatically update a model instance everytime another model instance is updated

Time:05-21

In online shop projects, I have a model called Order (and this model stores order instances) and a model called Points. The model Points stores bonus points which are collected by the users when they make orders. But the order may be cancelled, so I would like to be able to monitor when an order is being cancelled (model Order instance's status being changed to "cancelled") in order to take the points away. How can I do that?

CodePudding user response:

Use Django signals: https://docs.djangoproject.com/en/4.0/ref/signals/#django.db.models.signals.post_save

You can detect that Order instance was saved and which field exactly was updated and then do some logic when thsi happens.

Example:

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


@receiver(pre_save, sender=Order)
def post_save_order_handler(sender, instance, created, **kwargs):
    if not created:
    for item in iter(kwargs.get('update_fields')):
        if item == 'status' and instance.status == "cancelled":
           # do something here

Or you can similarily use pre_save signal and check if status changed from some valid status to cancelled before saving.

CodePudding user response:

can you share your models and functions? you can easily implements two more queries to maintain points for user using placing order and cancelling order Functions. for example

def place_order(request):
       Order.objects.create()
       Point.objects.create(user_id=user_id,points="10")

vice versa for Cancelling order update status of order and update the points to 0 or minus from total.

  • Related