Django signals dispatch_uid
Asked Answered
I

1

7

I have a question regarding the usage of dispatch_uid for signals.

Currently, I am preventing multiple usage of the signal by simply adding if not instance.order_reference. I wonder now if dispatch_uid has the same functionality and I can delete the "if not" clause.

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"
        )
Illboding answered 15/6, 2018 at 18:21 Comment(0)
T
4

As by 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

So yes, removing the if clause and setting a unique signal receiver dispatch_uid instead will prevent your handlers from being connected (and thereafter, called) more than once.

Tilney answered 15/6, 2018 at 18:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.