python - Django post_save() 信号实现

标签 python django django-models django-signals

我有一个关于 django 的问题。

我这里有 ManyToMany 模型

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()

关于python - Django post_save() 信号实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13014411/

相关文章:

django - 检查views.py中的 bool 字段状态

javascript - 反转 'export2',没有找到参数

sql - Django 。数据库查询: distinct for one field

Python - 将更改应用于整个列

python - 在带有 'safe' 参数的 utf-8 字符串上使用 python 的 urllib.quote_plus

python - Flask-SQLAlchemy ORM/GeoAlchemy2 结果为字典,最终为 JSON

Django 模型 validate_unique 方法不会引发 ValidationError

python - 在测试用例(单元测试)中,无法捕获 Django pre_save 信号

django - 尝试制作一个看起来不像我的模型的 django Rest api

python - 如何获取外键对象以在 django rest 框架中显示完整对象