Skip to content

Instantly share code, notes, and snippets.

@yuekui
Created November 4, 2020 00:59
Show Gist options
  • Save yuekui/2c51aa077e02901e75add2973dfe05cb to your computer and use it in GitHub Desktop.
Save yuekui/2c51aa077e02901e75add2973dfe05cb to your computer and use it in GitHub Desktop.
Temporarily disable Django signals for specific receiver
```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