- 在models保存之前触发
- 取消订单后原来从数据库中减的库存要加回库存
使用触发器在保存订单之前先执行加库存
在app下新建signal.py文件
- 第一步,编写receiver并绑定到signal
from django.dispatch import receiver
from django.db.models.signals import pre_save
@receiver(pre_save, sender=Models)
def func(sender, **kwargs):
pass
signal.py文件具体:
# -*- coding: utf-8 -*- from .models import OrderMain, OrderDetail from django.dispatch import receiver from django.db.models.signals import pre_save from django.db.models import F from django.db import transaction @receiver(pre_save, sender=OrderMain) def order_main_signal(sender, **kwargs): order = kwargs["instance"] if order.is_pay == "-1": details = OrderDetail.objects.filter(order=order) with transaction.atomic(): for od in