yanik
yanik

Reputation: 808

Django Signal on method call (not triggering model instance)

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.

Upvotes: 0

Views: 262

Answers (1)

rafalmp
rafalmp

Reputation: 4068

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.

Upvotes: 3

Related Questions