我有一个关于django的问题。
我这里有许多对多模型
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)
对于创建的1个购物车对象,我可以插入尽可能多的新TransactionDetail对象(产品和金额)。我的问题是。如何实现触发器?我想要的是每当创建交易明细时,我希望产品的存货数量减去交易明细中的数量。
我已经阅读了有关post_save()的信息,但不确定如何实现。也许像这样
什么时候:
post_save(TransactionDetail, Cart) #Cart object where TransactionDetail.cart= Cart.id Cart.stock -= TransactionDetail.amount
如果你真的想使用信号来实现这一目标,这里简单介绍一下,
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()