0

We have a model:

class Item(model.Model):
    pass

    def items_red(self):
        # filter items by red color
        # model instance is NOT changed (saved)
        pass

I need to catch Item.items_red() method execution with Django signal. Any suggestions how to do that? items_red not changing model instance in any way.

yanik
  • 798
  • 11
  • 33

1 Answers1

3

You need to define a custom signal:

import django.dispatch

items_red_executed = django.dispatch.Signal()

class Item(model.Model):
    pass

    def items_red(self):
        # filter items by red color
        # model instance is NOT changed (saved)
        items_red_executed.send(sender=self.__class__)

then a receiver:

from django.dispatch.dispatcher import receiver

@receiver(items_red_executed, sender=Item)
def my_receiver(**kwargs):
    print(kwargs.get('sender'))

For more information refer to the documentation.

rafalmp
  • 3,988
  • 3
  • 28
  • 34
  • Thx for an explanation, I don't use signals a lot. But now I understand its a bit overhead and would just create additional method, and trigger one in `items_red` – yanik Jul 24 '16 at 11:31
  • I don't think you have to worry much about that overhead, in DB-driven applications the biggest bottleneck is usually caused by your DB performance. – rafalmp Jul 24 '16 at 11:45
  • Still, code should as explicit as possible. It's helps when you support your project after couple month of coding – yanik Jul 24 '16 at 12:41