Django Signals-“ Created”参数变为false

时间:2018-09-27 18:54:19

标签: django django-signals

我在一个电子商务网站上工作,我使用信号来更新“订单”中的总价值。  -> post_save_cart_total()-每当创建新购物车时都会调用  -> post_save_order()-每当在购物车中创建或更改订单时都会调用  ->使用if语句(用于检查是否创建订单)下的post_save_order()调用的update_total()更新购物车值。  -> post_save_cart_total()完成后将调用post_save_order(){此功能仅在每次/每次创建新购物车时都被调用}  ->创建购物车后两次调用post_save_order()(post_save_cart_total())       -第一次填写订单的值       -第二次更新,每次更改订单时都会调用 问题  ->我在这里面临的问题是,       -第一次调用 post_save_order()时, created = True 的值将进入 if语句,并更新总计被调用以将值更新为订单       -第二次调用 post_save_order()时,created的值将更改为 created = False ,并且值不会更新为该顺序       -因此,每当我更改订单中的项目(添加/删除)时,购物车值就不会更改,(即)控件不会执行 if语句下的代码,如 created = False

`

def pre_save_create_order_id(sender, instance, *args, **kwargs):
if not instance.order_id:
    instance.order_id = unique_order_id_generator(instance)
    #instance.save() #--> Since pre_save signal is used here, this is not required
pre_save.connect(pre_save_create_order_id, sender=Order)

def post_save_order(sender, instance, created, *args, **kwargs):
    print('post_save_order')
    print('Before if, created = %s' %created)
    print('Running')
    #instance.update_total()
    if created:
        print('if stmnt, created = %s' %created)
        print('Updating - - - > First')
        instance.update_total()
    else:
        print('else stmnt, created = %s' %created)
        print('2nd entry')
        #instance.update_total()

post_save.connect(post_save_order, sender=Order)

--------->所有信号函数{post_save_cart_total(),post_save_order()}在Order类外部定义,update_total在Order类内部定义<--------- ----

def update_total(self): #This method is called when a cart changes he order size or when an order is created 
    cart_total = self.cart.total
    print(cart_total)
    shipping_total = self.shipping_total
    new_total = cart_total + shipping_total
    print(new_total)
    self.total = new_total
    self.save() 
    return new_total

`

Windows cmd日志:

[27/Sep/2018 14:16:22] "GET /admin/jsi18n/ HTTP/1.1" 200 3189
post_save_order
Before if, created = True
Running
if stmnt, created = True
Updating - - - > First
30.00
33.99
post_save_order
Before if, created = False
Running
else stmnt, created = False
2nd entry 

0 个答案:

没有答案