Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Fixed #280 -- Added _pre_delete() and _post_delete() hooks. Also upda…

…ted 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
  • Loading branch information...
commit b7e5121684afa36739c1aa9bbb96401645dbc417 1 parent 03bd1d7
@adrianholovaty adrianholovaty authored
Showing with 57 additions and 0 deletions.
  1. +6 −0 docs/model-api.txt
  2. +51 −0 tests/testapp/models/save_delete_hooks.py
View
6 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
--------------------
View
51 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()
+[]
+"""
Please sign in to comment.
Something went wrong with that request. Please try again.