简体   繁体   中英

How can I detect when objects of a Django model are added/deleted?

When adding or removing objects of Foo type I need to 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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM