Actions triggered by field change in Django

后端 未结 7 1039
囚心锁ツ
囚心锁ツ 2020-12-07 23:09

How do I have actions occur when a field gets changed in one of my models? In this particular case, I have this model:

class Game(models.Model):
    STATE_C         


        
相关标签:
7条回答
  • 2020-12-07 23:43

    Django has a nifty feature called signals, which are effectively triggers that are set off at specific times:

    • Before/after a model's save method is called
    • Before/after a model's delete method is called
    • Before/after an HTTP request is made

    Read the docs for full info, but all you need to do is create a receiver function and register it as a signal. This is usually done in models.py.

    from django.core.signals import request_finished
    
    def my_callback(sender, **kwargs):
        print "Request finished!"
    
    request_finished.connect(my_callback)
    

    Simple, eh?

    0 讨论(0)
提交回复
热议问题