Skip to content

Instantly share code, notes, and snippets.

@slacy
Created September 4, 2012 21:56
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save slacy/3627098 to your computer and use it in GitHub Desktop.
Save slacy/3627098 to your computer and use it in GitHub Desktop.
Django Model mixin for pushing signal handling back into instance methods.
class SignalModel(models.Model):
"""A Model mixin class that lets you put your signal handler methods back into your Model class."""
@classmethod
def _sig_pre_delete(cls, instance, *args, **kwargs):
"""dispatch the pre_delete method to a regular instance method. """
return instance.sig_pre_delete(*args, **kwargs)
@classmethod
def _sig_post_delete(cls, instance, *args, **kwargs):
"""dispatch the post_delete method to a regular instance method. """
return instance.sig_post_delete(*args, **kwargs)
@classmethod
def _sig_pre_save(cls, instance, *args, **kwargs):
"""dispatch the pre_save method to a regular instance method. """
return instance.sig_pre_save(*args, **kwargs)
@classmethod
def _sig_post_save(cls, instance, *args, **kwargs):
"""dispatch the post_save method to a regular instance method. """
return instance.sig_post_save(*args, **kwargs)
@classmethod
def connect(cls, signal):
"""Connect a django signal with this model."""
# List all signals you want to connect with here:
from django.db.models.signals import (pre_save, post_save, pre_delete, post_delete)
sig_handler = {
pre_save: cls._sig_pre_save,
post_save: cls._sig_post_save,
pre_delete: cls._sig_pre_delete,
post_delete: cls._sig_post_delete,
}[signal]
signal.connect(sig_handler, sender=cls)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment