Django Signal

首先在 app 目录下新建 signals.py 文件,写入类似于以下的内容

1
2
3
4
5
6
7
8
9
from django.dispatch import receiver

from [models] import [XXModel]
from [signals] import [XXSignal]

@receiver([XXSignal], sender=[XXSignal], dispatch_uid='some string')
def parse_signal(sender, **kwargs):
# do something
pass

其中,[XXModel] 为发送信号的实例(不一定是 model、不一定必须设置);[XXSignal] 是信号

设置完后,在相应应用的 apps.py 文件中注册此 receiver 即可

1
2
3
4
5
6
7
8
9
from django.apps import AppConfig

class XXXConfig(AppConfig):
name = 'xxx'
verbose_name = 'XXX'

def ready(self):
super().ready()
from . import signals

附:当 User 创建时自动创建 UserInfo

1
2
3
4
5
6
7
8
9
10
from django.db.models.signals import post_save
from django.dispatch import receiver

from .models import User, UserInfo

@receiver(post_save, sender=User, dispatch_uid='user_post_save')
def user_save(sender, instance, created, **kwargs):
if created:
ui = UserInfo(user=instance)
ui.save()