How can I detect when objects of a Django model are added/deleted?
When adding or removing objects of Foo
type I need t开发者_运维技巧o do the same calculation. How can I detect the adding/deleting of objects for Foo
model? For example:
from django.db import models
class Foo(models.Model):
...
def save(self):
#do some processing
def delete(self):
#do some processing
Can I avoid the code duplication in these two methods?
Using signals you can implement it like
from django.db import models
from django.db.models.signals import post_save, post_delete
class Foo(models.Model):
...
...
def foo_handler(sender, **kwargs):
#do some processing
post_save.connect(foo_handler, sender=Foo)
post_delete.connect(foo_handler, sender=Foo)
You should use Django's signals to call a particular function before or after a model is saved or deleted (and also at other times, if need be). Check out the relevant documentation here: http://docs.djangoproject.com/en/dev/topics/signals/
If you override the model methods, your delete()
will not be invoked when deleting object in bulk from a queryset (see here).
You may connect several signals to the same method using signal.connect
.
精彩评论