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
这是一个例子
This might seem a bit confusing right now if you are a beginner, but le