Login

Model Hooks

Author:
jakecr
Posted:
January 6, 2010
Language:
Python
Version:
1.1
Tags:
model hooks
Score:
5 (after 5 ratings)

Runs model methods on save, create, update, delete Similar to Rails hooks

Usage: in models.py

from myproject.hooks import connect_hooks

class MyModel(models.Model):

#...

# only on first save of a newly created object
def before_create(self): print self
def after_create(self): print self

# not on first save of a newly created object
def before_update(self): print self
def after_update(self): print self

# any save, new object or update
def before_save(self): print self
def after_save(self): print self

# delete, self is still available after delete
def before_delete(self): print self
def after_delete(self): print self

connect_hooks(MyModel)

 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 6 years, 3 months ago
  2. Class based generic views that automatically check permissions by humphreymurray 4 years, 4 months ago
  3. Custom model field for Frame or Box by binishkaspar 4 years, 3 months ago
  4. Google Geocode Lookup by tonyskyday 7 years, 11 months ago
  5. Automatic Memoization Decorator by nikmolnar 2 years, 4 months ago

Comments

jakecr (on January 6, 2010):

Improvements and suggestions welcome

#

Please login first before commenting.