例子,建立數據庫記錄,觸發pre_save和post_save信號
建立一個Django項目,配置好路由映射
models.py中的代碼:
from django.db import models
class UserInfo(models.Model):
name=models.CharField(max_length=32)
pwd=models.CharField(max_length=64)
views.py中的代碼:
from django.shortcuts import render,HttpResponse
from app01 import models
def index(request):
models.UserInfo.objects.create(name="mysql",pwd="mysql123")
return HttpResponse("ok")
項目的__init__.py文件中代碼:
from django.db.models.signals import pre_save,post_save
def pre_save_func(sender,**kwargs):
print("pre_save_func")
print("pre_save_msg:",sender,kwargs)
def post_save_func(sender,**kwargs):
print("post_save_func")
print("post_save_msg:",sender,kwargs)
pre_save.connect(pre_save_func) # models對象保存前觸發callback函數
post_save.connect(post_save_func) # models對象保存後觸發函數
建立一個index.html網頁,用瀏覽器打開這個項目,在服務端後臺打印信息以下:
pre_save_func
pre_save_msg: <class 'app01.models.UserInfo'> {'signal': <django.db.models.signals.ModelSignal object at 0x0000000002E62588>,
'instance': <UserInfo: UserInfo object>, 'raw': False, 'using': 'default', 'update_fields': None}
post_save_func
post_save_msg: <class 'app01.models.UserInfo'> {'signal': <django.db.models.signals.ModelSignal object at 0x0000000002E62630>,
'instance': <UserInfo: UserInfo object>, 'created': True, 'update_fields': None, 'raw': False, 'using': 'default'}
比較打印的結果,能夠看到models對象保存後,在打印信息裏包含一個"create=True"的鍵值對.
也能夠使用裝飾器來觸發信號,把上面__init__.py中的代碼修改:
from django.core.signals import request_finished
from django.dispatch import receiver
@receiver(request_finished)
def callback(sender, **kwargs):
print("Request finished!")
則在本次請求結束後自動觸發callback函數,在後臺"request finished"這句話.