I have a model looking like this:
class Recipe(models.Model):
name = models.CharField(_('Name'))
components = models.ManyToManyField(RecipeComponent, through='alchemy.RecipeComposition')
total_weight = models.FloatField(_('How much recipe will weight'))
class RecipeComponent(models.Model):
name = models.CharField(_('Name'))
class RecipeComposition(models.Model):
recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE)
component = models.ForeignKey(RecipeComponent, on_delete=models.CASCADE)
number = models.FloatField(_('Defines how much of the component you need'), default=1)
I have to do some calculations (for example total weight) of the recipe after any updates in RecipeComposition.
Trying to do like this unfortunately doesn't help:
@receiver(m2m_changed, sender=Recipe.components.through, weak=False)
def recipe_components_changed(sender, **kwargs):
print("meow >^-_-^<")
# some calculations for recipe.total_weight here
Found question with same problem but it's old (3 yrs ago) and has no correct answer. There is a link to ticket 17688 there which is opened 6 yrs ago but still not solved.
I do not want to use post_save like this:
@receiver(post_save, sender=RecipeComposition)
because in this case when new Recipe created total_weight will be recalculated after each component added.
Are there any other ideas how to make this work?