Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse code

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
  • Loading branch information...
commit 0fc2a2c1a891a9729f99b550bca6334e97c0dce3 1 parent be57a7f
Adrian Holovaty authored May 22, 2006
2  docs/db-api.txt
@@ -345,7 +345,7 @@ This is roughly equivalent to::
345 345
 
346 346
     Entry.objects.order_by('headline')[0:1].get()
347 347
 
348  
-Note, however, that the first of these will raise ``IndexError`` while the 
  348
+Note, however, that the first of these will raise ``IndexError`` while the
349 349
 second will raise ``DoesNotExist`` if no objects match the given criteria.
350 350
 
351 351
 QuerySet methods that return new QuerySets
33  docs/model-api.txt
@@ -1599,6 +1599,39 @@ API. See `Other lookup options`_.
1599 1599
 .. _Python DB-API: http://www.python.org/peps/pep-0249.html
1600 1600
 .. _Other lookup options: http://www.djangoproject.com/documentation/db_api/#extra-params-select-where-tables
1601 1601
 
  1602
+Overriding default model methods
  1603
+--------------------------------
  1604
+
  1605
+As explained in the `database API docs`_, each model gets a few methods
  1606
+automatically -- most notably, ``save()`` and ``delete()``. You can override
  1607
+these methods to alter behavior.
  1608
+
  1609
+A classic use-case for overriding the built-in methods is if you want something
  1610
+to happen whenever you save an object. For example::
  1611
+
  1612
+    class Blog(models.Model):
  1613
+        name = models.CharField(maxlength=100)
  1614
+        tagline = models.TextField()
  1615
+
  1616
+    def save(self):
  1617
+        do_something()
  1618
+        super(Blog, self).save() # Call the "real" save() method.
  1619
+        do_something_else()
  1620
+
  1621
+You can also prevent saving::
  1622
+
  1623
+    class Blog(models.Model):
  1624
+        name = models.CharField(maxlength=100)
  1625
+        tagline = models.TextField()
  1626
+
  1627
+    def save(self):
  1628
+        if self.name == "Yoko Ono's blog":
  1629
+            return # Yoko shall never have her own blog!
  1630
+        else:
  1631
+            super(Blog, self).save() # Call the "real" save() method.
  1632
+
  1633
+.. _database API docs: http://www.djangoproject.com/documentation/db_api/
  1634
+
1602 1635
 Models across files
1603 1636
 ===================
1604 1637
 

0 notes on commit 0fc2a2c

Please sign in to comment.
Something went wrong with that request. Please try again.