Created
September 4, 2012 21:56
-
-
Save slacy/3627098 to your computer and use it in GitHub Desktop.
Django Model mixin for pushing signal handling back into instance methods.
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
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