Django:保存多个对象信号一次 [英] Django: save multiple object signal once

查看:215
本文介绍了Django:保存多个对象信号一次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

订单放置时,我需要一些帮助来发送电子邮件。为了说明问题,以下是抽象代码:

I need some help with sending email when an order is placed. To illustrate the problem, following is the abstract code:

class Order(models.Model):
    user = models.ForeignKey(User)

class OrderItem(modes.Model):
    order = models.ForeignKey(Order, related_name='items')
    item = models.CharField(max_length=255)
    unit_price = models.DecimalField()
    qty = models.IntegerField()
    item_amount = models.DecimalField()

def email_order_on_save(sender, instance, **kwargs):
    # Need order.items.all() here
    pass

post_save.connect(email_order_on_save, sender=Order)

SO和谷歌上的大多数问题似乎一次处理一个子对象; 如此

Most of the problems on SO and google seem to deal with one child object at a time; such as this.

如果从管理员内嵌中保存5个订单项,聆听OrderItem将释放5个信号。我似乎无法摆脱这个问题。一种方式,我认为(不确定是否可能),最后可能会听(5)OrderItem的post_save信号。

Listening to OrderItem would release 5 signals if 5 orders items saved from admin inlines. I can't seem to get my head around this problem. One way, I think (not sure if possible), could be listening to last of all(5) OrderItem's post_save signals.

任何帮助赞赏。

推荐答案

创建自己的自定义信号,并在您需要保存数据时发送。作为参数传入您需要的任何数据结构。

Create your own custom signal and send it at the point when you have the data you need saved. Pass in as parameters whatever data structures you need.

在您的回调函数 email_order_on_save 中收听您的自定义信号,并根据有关发送或不发送电子邮件的参数做出适当的决定。

Listen for your custom signal in your callback function email_order_on_save and make appropriate decisions based on the parameters about sending or not the e-mail.

这篇关于Django:保存多个对象信号一次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆