Created
November 4, 2020 00:59
-
-
Save yuekui/2c51aa077e02901e75add2973dfe05cb to your computer and use it in GitHub Desktop.
Temporarily disable Django signals for specific receiver
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
```python3 | |
from contextlib import contextmanager | |
from django.db.models.signals import * | |
@contextmanager | |
def disable_signals(sender, receiver, *signals): | |
if not signals: | |
signals = [pre_init, post_init, pre_save, post_save, pre_delete, post_delete] | |
disconnected_signals = [] | |
for signal in signals: | |
if signal.disconnect(receiver, sender): | |
disconnected_signals.append(signal) | |
try: | |
yield | |
finally: | |
for signal in disconnected_signals: | |
signal.connect(receiver, sender) | |
# Example usage: | |
# with disable_signals(user.__class__, some_func, post_save): | |
# user.save() # will not call any signals | |
``` | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment