Django Signals-掌握pre_save和post_save

Django, with it’s experienced developer community and regular updates have become a reliable framework to build stable and maintainable websites. Not to forget the easy-to-understand the documentation it provides, makes it easier for the beginners to get their way started in Django

Django,凭借其经验丰富的开发人员社区和定期更新,已成为构建稳定且可维护的网站的可靠框架。 别忘了它提供的易于理解的文档 ,使初学者更容易在Django中入门

Without wasting much time on what Django is, let’s jump right into one of it’s most crucial topics- Signals

在不花太多时间讨论Django是什么的情况下,让我们直接进入它最重要的主题之一- 信号

什么是信号 (What are Signals)

Signals, as the name suggests, allow applications to get notified when a certain event occurs. Suppose you want to notify the author of an article whenever someone comments or reacts on the article, but there are several places in your codebase to comment on an article or react on the article. How do you do it? You guessed it right, using signals. Signal hooks some piece of code to be executed as soon as a specific model’s save method is triggered.

顾名思义,信号允许应用程序在发生特定事件时得到通知 。 假设您想在有人发表评论或对文章做出React时通知文章作者,但是您的代码库中有很多地方可以评论文章或对文章做出React。 你怎么做呢? 您使用信号猜对了。 特定模型的保存方法一被触发,Signal就会钩住要执行的某些代码。

To have a clearer idea of the above example, let’s define the models.

为了更清楚地了解上面的示例,让我们定义模型。

何时使用信号 (When to use Signals)

Signals are best used when multiple pieces of code are interested in the same model instance events. To understand model instance events in simpler terms, it means a row creation, updating or deletion events.

当多个代码段对同一模型实例事件感兴趣时,最好使用信号。 为了用更简单的术语理解模型实例事件,这意味着创建行,更新或删除事件。

如何使用信号 (How to use Signals)

While there are many ways to use signals, my favourite way is to use the ‘@receiver’ decorator.

尽管有很多使用信号的方法,但我最喜欢的方法是使用'@receiver'装饰器。

Here is an example

这是一个例子

Image for post
signals.py
signal.py

This might seem a bit confusing right now if you are a beginner, but le

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值