3

I am working on Django Signals to handle data in Redis whenever any change happens in the Postgres database. But, I am unable to send custom parameters to Signal Receiver. I have gone through a lot of questions, but I am not able to understand how to send extra custom parameters to Signal Receiver.

Usually I do,

@receiver(post_save, sender=post_data)
def addToRedis(sender, instance, **kwargs):

But I want to do,

@receiver(post_save, sender=post_data)
def addToRedis(sender, instance, extra_param=extra_param_data **kwargs):
  # Get `extra_param`

Here, I want to read extra_param to store the data in Redis.

I am using Django Rest Framework. And post_save is directly called after serializer.save()

It'll be great if someone can help me out in this.

user2538076
  • 173
  • 1
  • 2
  • 18
  • Possible duplicate of [Passing arguments django signals - post\_save/pre\_save](http://stackoverflow.com/questions/22999630/passing-arguments-django-signals-post-save-pre-save) – Eugene Soldatov Oct 12 '15 at 09:08

2 Answers2

4

You can send any additional parameters in a signal as keyword arguments:

@receiver(post_save, sender=post_data)
def addToRedis(sender, instance, **kwargs):
    # kwargs['extra_param']

How to send:

my_signal.send(sender=self.__class__, extra_param='...')

If you have no access to the signal send function (eg REST framework internals), you can always use a custom signal.

Wtower
  • 18,848
  • 11
  • 103
  • 80
  • I am getting KeyError in extra_param. I am using Django Rest Framework & I guess serializer.save() is calling receiver directly after post_save. Hence, key is not passed which results in error. Any solution? – user2538076 Oct 12 '15 at 10:32
  • If the signal send does not provide the additional parameter, it is reasonable that the receiver doesn't get it... You should provide more info in your question. No idea about how the rest framework deals with events. You can always implement your custom signals anyway. – Wtower Oct 12 '15 at 10:42
  • It doesn't worth it, you need to call it explicitly and the purpose of signals is to be called automatically. – wrivas Aug 21 '20 at 15:44
3

This Answer the with Respect to Django Rest:

in your views.py

my_obj = Mymodel()
my_obj.your_extra_param = "Param Value" # your_extra_param field (not Defined in Model)
my_obj.save()
post_save.connect(rcver_func,sender=Mymodel,weak=False)

and define a signal.py with following

from django.db.models.signals import post_save
from django.dispatch import receiver
from .models import Mymodel

@receiver(post_save,sender=Mymodel)
def rcver_func(sender, instance, created,**kwargs):
    if created:
        received_param_value = instance.your_extra_param # same field as declared in views.py
Lubdhak
  • 106
  • 1
  • 8