使用post_save信号处理程序访问新创建的模型实例的相关数据 [英] Access to related data of newly created model instance using post_save signal handler

查看:74
本文介绍了使用post_save信号处理程序访问新创建的模型实例的相关数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通过管理面板创建 Entry 模型的新实例时,我需要发送电子邮件。因此,在 models.py 中,我有:

I need to send an e-mail when new instance of Entry model is created via admin panel. So in models.py I have:

class Entry(models.Model):   
    attachments = models.ManyToManyField(to=Attachment, blank=True)
    #some other fields
    #...
    sent = models.BooleanField(editable=False, default=False)

然后,我注册了post_save处理函数:

Then I'm registring post_save handler function:

def send_message(sender, instance, **kwargs):
    if not instance.sent:
        #sending an e-mail message containing details about related attachments
        #...
        instance.sent = True
        instance.save()

post_save.connect(send_message, sender=Entry)  

它可以工作,但是正如我之前提到的,我还需要访问相关附件以将其详细信息包括在信息。不幸的是,即使实际添加了附件, instance.attachments.all()也会在 send_message 函数内返回空列表。

It works, but as I mentioned before, I also need to access related attachments to include their details in the message. Unfortunatelly instance.attachments.all() returns empty list inside send_message function even if attachments were actually added.

我发现,发送post_save信号时,尚未保存已保存模型的相关数据,因此无法从该位置获取相关附件。
问题是:我是否可以使用信号或任何其他方式来完成此操作,还是必须将此电子邮件发送代码放在外面,例如,覆盖 Entry <的管理面板更改视图? / code>模型?

As I figured out, when the post_save signal is sent, related data of saved model isn't saved yet, so I can't get related attachments from that place. Question is: am I able to accomplish this using signals, or in any other way, or do I have to put this email sending code outside, for example overriding admin panel change view for Entry model?

推荐答案

您应该可以通过覆盖 save_model()方法。您可以在其中发送电子邮件,也可以发出自定义信号,触发您的处理程序发送电子邮件。

You should be able to do this by overriding the save_model() method on the ModelAdmin. You could either send your email in there or fire a custom signal which triggers your handler to send the email.

如果您有内联,我相信您需要使用 save_formset()

If you have inlines, I believe you need to use save_formset() instead.

这篇关于使用post_save信号处理程序访问新创建的模型实例的相关数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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