Login

Model Hooks

Author:
jakecr
Posted:
January 6, 2010
Language:
Python
Version:
1.1
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. Template tag - list punctuation for a list of items by shapiromatron 10 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 6 months ago

Comments

jakecr (on January 6, 2010):

Improvements and suggestions welcome

#

Please login first before commenting.