| | 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 | |
|---|