【发布时间】:2021-12-17 15:10:18
【问题描述】:
我正在尝试实现一个功能,该功能在发布新文档记录时向所有员工记录发送通知。在模型中,我仍然需要导入接收器函数,因为我的发送器模型位于不同的项目中:
receiver 函数(位于项目中的不同应用程序中):
def new_document_version_published(sender, instance, **kwargs):
print("New version of document published!")
print(sender)
print(instance)
# Get all employees
employees = []
# Send notifications to employees
buttons = [NotificationButton(button_text="New version of document", value="Ok", style="primary")]
notifyUsers("A new version of the document has been published", buttons, employees, [])
发件人(位于项目中的不同应用程序中):
from django.db.models.signals import post_save
from api.views import new_document_version_published
class DocumentVersion:
...
def save(self, *args, **kw):
if self.pk is not None:
orig = DocumentVersion.objects.get(pk=self.pk)
if orig.date_published != self.date_published:
print('date_published changed')
notify_employees()
if orig.date_approved != self.date_approved:
print('date_approved changed')
super(DocumentVersion, self).save(*args, **kw)
def notify_employees():
post_save.connect(new_document_version_published, sender=DocumentVersion)
我知道我的实现有问题,因为我不明白使用信号与仅导入和调用接收器函数之间有什么区别。感谢所有帮助!
【问题讨论】:
-
信号用于文件
helps decoupled applications get notified when actions occur elsewhere in the framework中的情况。当然你可以在每次调用动作时只导入接收函数,或者你只需要用信号写1次
标签: python django django-rest-framework signals