Fixed #280 -- Added _pre_delete() and _post_delete() hooks. Also updated the docs and added a unit testdjango/core/meta/__init__.py

git-svn-id: http://code.djangoproject.com/svn/django/trunk@432 bcc190cf-cafb-0310-a4f2-bffc1f526a37
This commit is contained in:
Adrian Holovaty 2005-08-08 18:29:02 +00:00
parent 03bd1d7ff9
commit b7e5121684
2 changed files with 57 additions and 0 deletions

View File

@ -728,6 +728,12 @@ There are a few object methods that have special meaning:
This method is called just after the object is saved to the database. This This method is called just after the object is saved to the database. This
could be used to update other tables, update cached information, etc. could be used to update other tables, update cached information, etc.
``_pre_delete``
Like ``_pre_save``, but for deletion.
``_post_delete``
Like ``_post_save``, but for deletion.
Module-level methods Module-level methods
-------------------- --------------------

View File

@ -0,0 +1,51 @@
"""
13. Adding hooks before/after saving and deleting.
Django provides hooks for executing arbitrary code around ``save()`` and
``delete()``. Just add any of the following methods to your model:
* ``_pre_save()`` is called before an object is saved.
* ``_post_save()`` is called after an object is saved.
* ``_pre_delete()`` is called before an object is deleted.
* ``_post_delete()`` is called after an object is deleted.
"""
from django.core import meta
class Person(meta.Model):
fields = (
meta.CharField('first_name', maxlength=20),
meta.CharField('last_name', maxlength=20),
)
def __repr__(self):
return "%s %s" % (self.first_name, self.last_name)
def _pre_save(self):
print "Before save"
def _post_save(self):
print "After save"
def _pre_delete(self):
print "Before deletion"
def _post_delete(self):
print "After deletion"
API_TESTS = """
>>> p1 = persons.Person(first_name='John', last_name='Smith')
>>> p1.save()
Before save
After save
>>> persons.get_list()
[John Smith]
>>> p1.delete()
Before deletion
After deletion
>>> persons.get_list()
[]
"""