Django

Code

Changeset 2955

Show
Ignore:
Timestamp:
05/21/06 22:01:02 (2 years ago)
Author:
adrian
Message:

Added 'Overriding default model methods' section to model-api.txt

Files:

Legend:

Unmodified
Added
Removed
Modified
Copied
Moved
  • django/trunk/docs/db-api.txt

    r2908 r2955  
    346346    Entry.objects.order_by('headline')[0:1].get() 
    347347 
    348 Note, however, that the first of these will raise ``IndexError`` while the  
     348Note, however, that the first of these will raise ``IndexError`` while the 
    349349second will raise ``DoesNotExist`` if no objects match the given criteria. 
    350350 
  • django/trunk/docs/model-api.txt

    r2953 r2955  
    16001600.. _Other lookup options: http://www.djangoproject.com/documentation/db_api/#extra-params-select-where-tables 
    16011601 
     1602Overriding default model methods 
     1603-------------------------------- 
     1604 
     1605As explained in the `database API docs`_, each model gets a few methods 
     1606automatically -- most notably, ``save()`` and ``delete()``. You can override 
     1607these methods to alter behavior. 
     1608 
     1609A classic use-case for overriding the built-in methods is if you want something 
     1610to 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 
     1621You 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 
    16021635Models across files 
    16031636===================