Django 信号 dispatch_uid

Django signals dispatch_uid

我对 dispatch_uid 信号的使用有疑问。

目前,我通过简单地添加 if not instance.order_reference 来防止信号的多次使用。我现在想知道 dispatch_uid 是否具有相同的功能,我可以删除 "if not" 子句。

signals.py

def reserveditem_create_order_reference(sender, instance, **kwargs):
    if not instance.order_reference:
        instance.order_reference = unique_order_reference_generator()

app.py

class OrdersConfig(AppConfig):
    name = 'orders'

    def ready(self):

        #Pre save signal for ReservedItem model
        reserved_model = self.get_model('ReservedItem')
        pre_save.connect(
            reserveditem_create_order_reference,
            sender=reserved_model,
            dispatch_uid="my_unique_identifier"
        )

根据 the docs,

In some circumstances, the code connecting receivers to signals may run multiple times. This can cause your receiver function to be registered more than once, and thus called multiple times for a single signal event. If this behavior is problematic (such as when using signals to send an email whenever a model is saved), pass a unique identifier as the dispatch_uid argument to identify your receiver function

所以是的,删除 if 子句并设置一个唯一的信号接收器 dispatch_uid 将防止您的处理程序被多次连接(然后被调用)。