Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
592 views
in Technique[技术] by (71.8m points)

python - Django post save signal getting called twice despite uid

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):

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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

Edit:

post_save was getting called twice because I used .create(...) which is equivalent to __init__(...) and .save().

Conclusion

dispatch_uid does work and doing single imports is still a good practice.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...