Sort django signal's receivers

家住魔仙堡 提交于 2021-01-29 10:46:42

问题


Django calls receiver methods in its own way. Is there any way that we can sort the receivers of Django signal? I didn't find anything related to it in official Django documentation.


回答1:


Unless I'm mistaken, there isn't any reason to have more than one receiver for the same signal and sender. It is possible but I don't believe it is the right way to approach it and you will not have explicit control over the calling sequence of each.

If, for example, you have a set of duplicate signals (that do different things) like so:

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

That would work but the order of execution isn't explicitly known. However, you could rewrite it to something like this to explicitly state the order of execution:

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)



回答2:


https://docs.djangoproject.com/en/2.2/topics/signals/#listening-to-signals

"All of the signal’s receiver functions are called one at a time, in the order they were registered."

Try:

@receiver(signals.pre_save, sender=User)
def signal_receiver_1(*args, **kwargs):
    print('RECEIVER 1')

@receiver(signals.pre_save, sender=User)
def signal_receiver_2(*args, **kwargs):
    print('RECEIVER 2')

@receiver(signals.pre_save, sender=User)
def signal_receiver_3(*args, **kwargs):
    print('RECEIVER 3')

Output will be:

RECEIVER 1
RECEIVER 2
RECEIVER 3

And then mix it up...



来源:https://stackoverflow.com/questions/52084499/sort-django-signals-receivers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!