M
M
Maxim2014-05-06 09:13:01
Django
Maxim, 2014-05-06 09:13:01

How to simplify signal code in Django?

Before each save of a certain list of models, I need to do some calculations.

@receiver(pre_save, sender=Model6)
@receiver(pre_save, sender=Model5)
@receiver(pre_save, sender=Model4)
@receiver(pre_save, sender=Model3)
@receiver(pre_save, sender=Model2)
@receiver(pre_save, sender=Model1)
def recalculate_data(instance, **kwargs):
    ...

In principle, everything suits me, but I would like to get rid of so many decorators, but the thought of how to do this does not occur to me. There is only an assumption that the recevier also needs to be decorated.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Yeletsky, 2014-05-06
@Masik

Write a decorator that accepts a list of models and internally wraps a @receiver function for each of them.
More or less like this.

def my_receiver(models):

    def decorator(func):
        for model in models:
            func = receiver(pre_save, sender=model)(func)
        return func

    return decorator

@my_receiver(models=[Model1, Model2, Model3])
def recalculate_data(instance, **kwargs):
    pass

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question