From 0fc2a2c1a891a9729f99b550bca6334e97c0dce3 Mon Sep 17 00:00:00 2001 From: Adrian Holovaty Date: Mon, 22 May 2006 03:01:02 +0000 Subject: [PATCH] Added 'Overriding default model methods' section to model-api.txt git-svn-id: http://code.djangoproject.com/svn/django/trunk@2955 bcc190cf-cafb-0310-a4f2-bffc1f526a37 --- docs/db-api.txt | 2 +- docs/model-api.txt | 33 +++++++++++++++++++++++++++++++++ 2 files changed, 34 insertions(+), 1 deletion(-) diff --git a/docs/db-api.txt b/docs/db-api.txt index e2173afe16..4442a75125 100644 --- a/docs/db-api.txt +++ b/docs/db-api.txt @@ -345,7 +345,7 @@ This is roughly equivalent to:: Entry.objects.order_by('headline')[0:1].get() -Note, however, that the first of these will raise ``IndexError`` while the +Note, however, that the first of these will raise ``IndexError`` while the second will raise ``DoesNotExist`` if no objects match the given criteria. QuerySet methods that return new QuerySets diff --git a/docs/model-api.txt b/docs/model-api.txt index 6ceabf4e3d..15192fcbb7 100644 --- a/docs/model-api.txt +++ b/docs/model-api.txt @@ -1599,6 +1599,39 @@ API. See `Other lookup options`_. .. _Python DB-API: http://www.python.org/peps/pep-0249.html .. _Other lookup options: http://www.djangoproject.com/documentation/db_api/#extra-params-select-where-tables +Overriding default model methods +-------------------------------- + +As explained in the `database API docs`_, each model gets a few methods +automatically -- most notably, ``save()`` and ``delete()``. You can override +these methods to alter behavior. + +A classic use-case for overriding the built-in methods is if you want something +to happen whenever you save an object. For example:: + + class Blog(models.Model): + name = models.CharField(maxlength=100) + tagline = models.TextField() + + def save(self): + do_something() + super(Blog, self).save() # Call the "real" save() method. + do_something_else() + +You can also prevent saving:: + + class Blog(models.Model): + name = models.CharField(maxlength=100) + tagline = models.TextField() + + def save(self): + if self.name == "Yoko Ono's blog": + return # Yoko shall never have her own blog! + else: + super(Blog, self).save() # Call the "real" save() method. + +.. _database API docs: http://www.djangoproject.com/documentation/db_api/ + Models across files ===================