Django post save signal getting called twice despite uid

前端 未结 4 1502
[愿得一人]
[愿得一人] 2020-12-16 21:59

I have registered my signal with the callback using the @receiver decorator

@receiver(post_save, sender=User, dispatch_uid=\'ARandomUniqueString         


        
4条回答
  •  萌比男神i
    2020-12-16 22:33

    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.

提交回复
热议问题