在 Django 管理中,我怎样才能知道布尔值第一次被设置为 true

发布于 2024-08-10 07:41:45 字数 154 浏览 2 评论 0原文

我有一个模型,其中包含一个表示该项目是否批准的布尔字段。 我想在选中该框后发送电子邮件。

我了解如何覆盖保存方法并发送电子邮件(如果是),但这将在每次保存时发送电子邮件。

由于我只想发送一次电子邮件,有没有办法仅在第一次检查布尔值是否为真?

谢谢

I have a model that contains a boolean field representing the item's approval or not.
I'd like to send an email when the box is checked.

I understand how to override the save method and send the email if it's true but this will send an email every time it's saved.

As I only want to send the email once, is there a way to check a boolean is true only for the first time?

Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

怪我鬧 2024-08-17 07:41:45

我所做的是在保存之前获取数据库中的元素,并将其与之后的内容进行比较。

def save(self):
    # Only when we update an element. Not when we create it
    if self.pk:
        # We get the old values of the model
        old = Model.objects.get(pk=self.pk)
        # If it's approved and it wasn't before
        if self.approved == True and old.approved == False:
            send_mail(...)
    super(Model, self).save()

因此,只有当对象从未批准变为已批准时才会发送电子邮件。

What I do is that I get the element as it's in the database before saving and I compare it to what I have after.

def save(self):
    # Only when we update an element. Not when we create it
    if self.pk:
        # We get the old values of the model
        old = Model.objects.get(pk=self.pk)
        # If it's approved and it wasn't before
        if self.approved == True and old.approved == False:
            send_mail(...)
    super(Model, self).save()

So the email will be send only when the object goes from not approved to approved.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文