问题
Say I have two models:
class Product(models.Model):
product = model.CharField()
quantity = model.IntegerField()
class sale(models.Model)
product = models.ManyToManyField(Product)
number_sold = model. IntegerField()
When a sale is made, I'd like the product quantity to be updated. Are signals the best way of going about this?
I was thinking about having sale admit a post_save signal when an object is created or updated. If updated, I would have to know the old and the new values to adjust the quantity properly. The product table would have to be listening for this signal.
I was also thinking about having the product table send a custom signal after it updates the quantity. If quantity < 0 item is on back order, else "success".
I am new to django and signals, but is this an appropriate use for signals or is their a better way to do this? I have read the docs, and watched a pycon video on signals, and read a few examples. I have yet to see signals used in this way, but I can't think of any other way to accomplish this task.
This is how I ended up accomplishing my goal, I am very interested to know if this is the proper way of doing this. I apologize for the models not matching the code below, I simplified my models to make it easier.
@receiver(pre_save, sender=Customer_Order_Products)
def update_quantity(sender, **kwargs):
obj = kwargs['instance']
updated_product = Inventory.objects.get(title = obj.product_id)
if not obj.id:
updated_product.quantity -= obj.quantity
else:
updated_product.quantity -= (obj.quantity - Customer_Order_Products.objects.get(id = obj.id).quantity)
Inventory.save(updated_product)
来源:https://stackoverflow.com/questions/13954499/django-signals-to-update-a-different-model