1

Imagine I have the two models Pizza and Topping and the Pizza model has a last_changed field with auto_now=True and a ManyToMany relationship to Topping.

I now want the last_changed field to be updated whenever I add another Topping to the Pizza. Unfortunately this is not updated automatically since the Pizza model does not get saved in such a case. This is because the ManyToMany relationship is held in a separate (auto created) model and table.

So what would be the best approach to update the last_changed field?

Raphaël Gomès
  • 938
  • 1
  • 8
  • 23
Fabian
  • 5,476
  • 4
  • 35
  • 46

1 Answers1

0

You can have a method on your Pizza model that gets called whenever you add a Topping to it.

class Pizza(models.Model):
    toppings = models.ManyToManyField('Toppings', related_name="pizzas")
    last_changed = models.DateTimeField(auto_now=True, blank=True)
    # Your other fields here

    def add_topping(self, topping):
        self.toppings.add(topping)
        self.save()  # Which would update last_changed

But I would also recommend against the use of auto_now (see this link).

Community
  • 1
  • 1
Raphaël Gomès
  • 938
  • 1
  • 8
  • 23
  • Sorry for the late reply and thanks for your suggestion. I just wonder how to enforce that everyone calls the add_topping method. If I have to enforce this, I could directly enforce everyone to just call the save(). – Fabian Feb 23 '17 at 21:07
  • @Fabian: how do you mean enforce? Do you not write the code? Sorry if I don't understand – Raphaël Gomès Feb 25 '17 at 13:14