Answer the question
In order to leave comments, you need to log in
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):
...
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question