From b7e5121684afa36739c1aa9bbb96401645dbc417 Mon Sep 17 00:00:00 2001 From: Adrian Holovaty Date: Mon, 8 Aug 2005 18:29:02 +0000 Subject: [PATCH] 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 --- docs/model-api.txt | 6 +++ tests/testapp/models/save_delete_hooks.py | 51 +++++++++++++++++++++++ 2 files changed, 57 insertions(+) create mode 100644 tests/testapp/models/save_delete_hooks.py diff --git a/docs/model-api.txt b/docs/model-api.txt index dbbe3e2c01..f071c1bfcb 100644 --- a/docs/model-api.txt +++ b/docs/model-api.txt @@ -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 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 -------------------- diff --git a/tests/testapp/models/save_delete_hooks.py b/tests/testapp/models/save_delete_hooks.py new file mode 100644 index 0000000000..dfff112d7f --- /dev/null +++ b/tests/testapp/models/save_delete_hooks.py @@ -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() +[] +"""