models.py 1.0 KB

1234567891011121314151617181920212223242526272829303132333435
  1. """
  2. Adding hooks before/after saving and deleting
  3. To execute arbitrary code around ``save()`` and ``delete()``, just subclass
  4. the methods.
  5. """
  6. from __future__ import unicode_literals
  7. from django.db import models
  8. from django.utils.encoding import python_2_unicode_compatible
  9. @python_2_unicode_compatible
  10. class Person(models.Model):
  11. first_name = models.CharField(max_length=20)
  12. last_name = models.CharField(max_length=20)
  13. def __init__(self, *args, **kwargs):
  14. super(Person, self).__init__(*args, **kwargs)
  15. self.data = []
  16. def __str__(self):
  17. return "%s %s" % (self.first_name, self.last_name)
  18. def save(self, *args, **kwargs):
  19. self.data.append("Before save")
  20. # Call the "real" save() method
  21. super(Person, self).save(*args, **kwargs)
  22. self.data.append("After save")
  23. def delete(self):
  24. self.data.append("Before deletion")
  25. # Call the "real" delete() method
  26. super(Person, self).delete()
  27. self.data.append("After deletion")