Search code examples
pythondjangodjango-modelsdjango-signals

Django - Multiple post_save signals after create despite dispatch_uid


I'm having trouble preventing a post_save signal from firing multiple times after the creation of an object.

My signal is defined as follows:

@receiver(post_save, sender=Order, dispatch_uid='post_save_order')
def post_save_order(sender, **kwargs):
    instance = kwargs.get('instance')

    if instance.type == 'buy':
        delta = instance.quantity
    else:
        delta = instance.quantity * -1

    Balance.update(instance.user, instance.quote_currency, delta)

the signal is imported in orders/apps.py

class OrdersConfig(AppConfig):
    name = 'orders'

    def ready(self):
        super(OrdersConfig, self).ready()

        import orders.signals

When printing passed kwargs to the signal after 1 Order.create:

{'instance': object, 'signal': signal, 'using': 'default', 'update_fields': None, 'raw': False, 'created': True}
{'instance': object, 'signal': signal, 'using': 'default', 'update_fields': None, 'raw': False, 'created': False}

so apparently on a single creation, there is 1 post_save signal fired with args created: True and 1 with created: False. I don't think that the problem is that the signal may be imported multiple times, because I provided a dispatch_uid and a post_delete signal that is defined in the same file is not fired multiple times on a single deletion.

Can anyone enlighten me why this is happening? Thanks


Solution

  • Your signal post_save is not a problem, multiple save triggering it is.

    From what I can see you are doing save 2 times in which the first-time object is created and the second-time object is updated without any field changes.

    created

    A boolean; True if a new record was created.

    update_fields

    The set of fields to update as passed to Model.save(), or None if update_fields wasn’t passed to save().