Django以自己的方式调用接收方法。有什么方法可以对Django信号的接收器进行排序吗?我没有在Django官方文档中找到任何与之相关的内容。
除非我弄错了,否则没有任何理由为同一个signal
和sender
配备一个以上的接收器。这是可能的,但我不相信它是接近它的正确方法,你不会明确控制每个的调用顺序。
例如,如果您有一组重复信号(执行不同的操作),请执行以下操作:
from django.db.models import signals
from django.dispatch import receiver
from django.contrib.auth import get_user_model
User = get_user_model()
@receiver(signals.pre_save, sender=User)
def signal_receiver_1(*args, **kwargs):
pass
@receiver(signals.pre_save, sender=User)
def signal_receiver_2(*args, **kwargs):
pass
@receiver(signals.pre_save, sender=User)
def signal_receiver_3(*args, **kwargs):
pass
这可行,但执行顺序没有明确知道。但是,您可以将其重写为类似的内容以明确说明执行顺序:
from django.db.models import signals
from django.dispatch import receiver
from django.contrib.auth import get_user_model
User = get_user_model()
def signal_receiver_1(*args, **kwargs):
pass
def signal_receiver_2(*args, **kwargs):
pass
def signal_receiver_3(*args, **kwargs):
pass
@receiver(signals.pre_save, sender=User):
def pre_save_signal_receiver_master(*args, **kwargs):
signal_receiver_1(*args, **kwargs)
signal_receiver_2(*args, **kwargs)
signal_receiver_3(*args, **kwargs)