排序Django信号的接收器

时间:2018-08-29 19:06:41

标签: python django signals

Django以自己的方式调用接收器方法。有什么办法可以对Django信号的接收者进行排序?在官方的Django文档中没有找到任何与此相关的信息。

2 个答案:

答案 0 :(得分:0)

除非我弄错了,否则对于相同的<script> $(document).on('click', '.param-rule', function(e){ e.preventDefault(); var id=$(this).parent().parent().attr('id'); $.when( $.getScript( "{{ asset('admin/app-assets/vendors/js/vendors.min.js') }}" ), $.getScript( "{{ asset('admin/app-assets/vendors/js/tables/datatable/datatables.min.js') }}" ), $.getScript( "{{ asset('admin/app-assets/js/scripts/tables/datatables/datatable-basic.js') }}" ), $.Deferred(function( deferred ){ $( deferred.resolve ); }) ).done(function(){ $('.param-content').load(Routing.generate('backlogrule_index', { id: id}), function() { $(this).children(':first').unwrap(); }); $('.param-rule').addClass('active'); $('.param').removeClass('active'); }); }); </script> 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

答案 1 :(得分:0)

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

“信号的所有接收器功能都按照其注册的顺序一次被调用。”

尝试:

@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')

输出将是:

RECEIVER 1
RECEIVER 2
RECEIVER 3

然后将其混合...