Model Hooks

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
from django.db.models.signals import pre_delete, post_delete, post_save, pre_save

def connect_hooks(model):
    post_delete.connect(post_delete_hook, sender=model)
    pre_delete.connect(pre_delete_hook, sender=model)
    pre_save.connect(pre_save_hook, sender=model)
    post_save.connect(post_save_hook, sender=model)

def pre_save_hook(sender, **kwargs):
    if kwargs['instance'].id == None:
        call(sender, 'before_create', kwargs['instance'])
    else:
        call(sender, 'before_update', kwargs['instance'])
    call(sender, 'before_save', kwargs['instance'])
    
def post_save_hook(sender, **kwargs):
    if kwargs['created']:
        call(sender, 'after_create', kwargs['instance'])
    else:
        call(sender, 'after_update', kwargs['instance'])
    call(sender, 'after_save', kwargs['instance'])
    
def pre_delete_hook(sender, **kwargs):
    call(sender, 'before_delete', kwargs['instance'])
    
def post_delete_hook(sender, **kwargs):
    call(sender, 'after_delete', kwargs['instance'])
    
def call(sender, method, instance):
    func = getattr(sender, method, None)
    if callable(func):
        func(instance)

More like this

  1. Signal to post new saved objects to Twitter by arthurfurlan 5 years, 1 month ago
  2. Class based generic views that automatically check permissions by humphreymurray 3 years, 3 months ago
  3. Custom model field for Frame or Box by binishkaspar 3 years, 1 month ago
  4. Google Geocode Lookup by tonyskyday 6 years, 10 months ago
  5. Automatic Memoization Decorator by nikmolnar 1 year, 3 months ago

Comments

jakecr (on January 6, 2010):

Improvements and suggestions welcome

#

(Forgotten your password?)