You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

signals.py 2.1KB

5 years ago
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. from functools import partial
  2. from django.db.models.utils import make_model_tuple
  3. from django.dispatch import Signal
  4. class_prepared = Signal(providing_args=["class"])
  5. class ModelSignal(Signal):
  6. """
  7. Signal subclass that allows the sender to be lazily specified as a string
  8. of the `app_label.ModelName` form.
  9. """
  10. def _lazy_method(self, method, apps, receiver, sender, **kwargs):
  11. from django.db.models.options import Options
  12. # This partial takes a single optional argument named "sender".
  13. partial_method = partial(method, receiver, **kwargs)
  14. if isinstance(sender, str):
  15. apps = apps or Options.default_apps
  16. apps.lazy_model_operation(partial_method, make_model_tuple(sender))
  17. else:
  18. return partial_method(sender)
  19. def connect(self, receiver, sender=None, weak=True, dispatch_uid=None, apps=None):
  20. self._lazy_method(
  21. super().connect, apps, receiver, sender,
  22. weak=weak, dispatch_uid=dispatch_uid,
  23. )
  24. def disconnect(self, receiver=None, sender=None, dispatch_uid=None, apps=None):
  25. return self._lazy_method(
  26. super().disconnect, apps, receiver, sender, dispatch_uid=dispatch_uid
  27. )
  28. pre_init = ModelSignal(providing_args=["instance", "args", "kwargs"], use_caching=True)
  29. post_init = ModelSignal(providing_args=["instance"], use_caching=True)
  30. pre_save = ModelSignal(providing_args=["instance", "raw", "using", "update_fields"],
  31. use_caching=True)
  32. post_save = ModelSignal(providing_args=["instance", "raw", "created", "using", "update_fields"], use_caching=True)
  33. pre_delete = ModelSignal(providing_args=["instance", "using"], use_caching=True)
  34. post_delete = ModelSignal(providing_args=["instance", "using"], use_caching=True)
  35. m2m_changed = ModelSignal(
  36. providing_args=["action", "instance", "reverse", "model", "pk_set", "using"],
  37. use_caching=True,
  38. )
  39. pre_migrate = Signal(providing_args=["app_config", "verbosity", "interactive", "using", "apps", "plan"])
  40. post_migrate = Signal(providing_args=["app_config", "verbosity", "interactive", "using", "apps", "plan"])