'Django: How to automatically update a model instance everytime another model instance is updated

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?



Solution 1:[1]

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.

Solution 2:[2]

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.

Solution 3:[3]

You can use crossbeam's scoped threads. This API is also going to be part of the standard library.

fn worker(list: &Vec<&str>) {
    crossbeam::scope(|s| {
        s.spawn(|_| println!("list: {:?}", list));
    })
    .unwrap();
}

Playground.

(Though note that it is more idiomatic to take &[&str] than &Vec<&str>).

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Bartosz Stasiak
Solution 2
Solution 3 Chayim Friedman