Search code examples
pythondjangodjango-modelsdjango-rest-frameworkdjango-signals

Pass additional attributes with Django signals


Is there any way to pass additional parameters to instance I'm saving in DB to later access them after the instance is saved?

Brief example of my case:

I'm using Django's signals as triggers to events, like sending a confirmation email, executed by other processes, like workers.

I'm willing to specify which instance and when should trigger the event, and which should not: sometimes I want created/updated records to trigger series of events, and sometimes I want them to be processes silently or do some other actions.

One solution for this is saving desired behaviour for specific instance in model's field like JSONField and recover this behaviour at post_save, but this seems very ugly way of handlign such problem.

I'm using post_save signal as verification that instance was correctly saved in the DB, because I don't want to trigger event and a moment later something goes wrong while saving instance in DB.

Instances are saved through Django Forms, backend routines and RestFramework Seralizers


Solution

  • One solution is to use an arbitrary model instance attribute (not field) to store the desired state. For example:

    def my_view(request):
        ...
        instance._send_message = True if ... else False
        instance.save()
    
    @receiver(post_save, sender=MyModel)
    def my_handler(sender, instance, **kwargs):
        if instance._send_message:
            ...