-
-
Notifications
You must be signed in to change notification settings - Fork 29
Callbacks
Callbacks are remodel's way of hooking into an object's lifecycle and perform actions around certain moments. For instance, before an object is saved. Or after an object is deleted.
Here are the available callbacks:
-
before_save
andafter_save
; -
before_delete
andafter_delete
; -
after_init
.
Callback can be defined in two ways: either by defining an instance method with the callback's name:
from remodel.models import Model
class Shirt(Model):
def after_init(self):
self.wash()
def wash(self):
print 'Gotta wash a shirt after creating it...'
either by decorating an instance method with a callback:
from remodel.models import Model, after_save
class Prize(Model):
@after_save
def brag(self):
print 'I just won a prize!'
By using the second syntax, you could define multiple methods for the same callback. This represents a great advantage because it allows splitting a larger callback method into several smaller ones. You can even combine the two syntaxes!
Callbacks can raise an exception, in which case any further action is halted (e.g.: an exception raised in the before_save() callback won't execute save()).
Also note that callbacks are run for table level methods, such as create
or all
.