问题描述
我已经使用@receiver
装饰器在回调函数中注册了信号
I have registered my signal with the callback using the @receiver
decorator
@receiver(post_save, sender=User, dispatch_uid='ARandomUniqueString')
def do_callback(sender, **kwargs):
我已经将from app.signals import *
代码放入了__init__.py
中,并且可以看到它被导入了两次,并且我认为没有很好的方法来修复它,这可能是由于settings.py
中的installed apps
导致的.我不明白为什么尽管使用dispatch_uid
并且modelInstance.save
仅被调用一次,却仍然运行do_callback
两次.有什么建议吗?
I have put the from app.signals import *
code in __init__.py
and I can see that it gets imported twice and I do not think there is a good way to fix it, possibly happening due to installed apps
in settings.py
. I cannot understand why despite using dispatch_uid
and the modelInstance.save
being invoked only once, it still runs do_callback
twice. Any suggestions?
推荐答案
好,所以我将导入移动到了views.py
(或models.py
,并且只导入了一次,却被调用了两次).
Ok so I moved the import to views.py
(or models.py
and while it was getting imported only once, it was getting called twice.
问题是在创建和保存对象时会调用post_save
信号.我不知道为什么,所以我添加了一个现在可以解决的解决方法
The problem was that the post_save
signal was getting called when the object was created as well as saved. I have no idea why so I added a workaround which now works
created = False
#Workaround to signal being emitted twice on create and save
if 'created' in kwargs:
if kwargs['created']:
created=True
#If signal is from object creation, return
if created:
return
post_save
被调用了两次,因为我使用了.create(...)
,它等同于__init__(...)
和.save()
.
post_save
was getting called twice because I used .create(...)
which is equivalent to __init__(...)
and .save()
.
结论
dispatch_uid
确实有效,并且单次导入仍然是一个好习惯.
dispatch_uid
does work and doing single imports is still a good practice.
这篇关于尽管存在uid,但Django post save信号被调用了两次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!