I have a question about django.
I have ManyToMany Models here
class Product(models.Model): name = models.CharField(max_length=255) price = models.DecimalField(default=0.0, max_digits=9, decimal_places=2) stock = models.IntegerField(default=0) def __unicode__(self): return self.name class Cart(models.Model): customer = models.ForeignKey(Customer) products = models.ManyToManyField(Product, through='TransactionDetail') t_date = models.DateField(default=datetime.now()) t_sum = models.FloatField(default=0.0) def __unicode__(self): return str(self.id) class TransactionDetail(models.Model): product = models.ForeignKey(Product) cart = models.ForeignKey(Cart) amount = models.IntegerField(default=0)
For 1 cart object created, I can insert as many as new TransactionDetail object (the product and amount). My question is. How can I implement the trigger? What I want is whenever a Transaction detail is created, I want the amount of the product's stock is substracted by the amount in the transactiondetail.
I've read about post_save() but I'm not sure how to implement it. maybe something like this
when:
post_save(TransactionDetail, Cart) #Cart object where TransactionDetail.cart= Cart.id Cart.stock -= TransactionDetail.amount
In the example above, save_profile is our receiver function, User is the sender and post_save is the signal. You can read it as: Everytime when a User instance finalize the execution of its save method, the save_profile function will be executed. If you supress the sender argument like this: post_save.
There are 3 types of signal. pre_save/post_save: This signal works before/after the method save(). pre_delete/post_delete: This signal works before after delete a model's instance (method delete()) this signal is thrown.
pre_save. This is sent at the beginning of a model's save() method. Arguments sent with this signal: sender.
Django Signals - post_delete()To notify another part of the application after the delete event of an object happens, you can use the post_delete signal.
If you really want to use signals to achieve this, here's briefly how,
from django.db.models.signals import post_save from django.dispatch import receiver class TransactionDetail(models.Model): product = models.ForeignKey(Product) # method for updating @receiver(post_save, sender=TransactionDetail, dispatch_uid="update_stock_count") def update_stock(sender, instance, **kwargs): instance.product.stock -= instance.amount instance.product.save()
Personally I would override the TransactionDetail's save() method and in there save the new TransactionDetail and then run
self.product.stock -= self.amount self.product.save()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With