Search code examples
djangodjango-modelsmany-to-manyoverridingdjango-orm

Django overriden model save method returning old data


I may be tired and I'm not seeing something, but I've tried too much.

class Pizza(models.Model):
portion_size = models.ForeignKey('PortionSize', on_delete=models.PROTECT)
pizza_type = models.ForeignKey('PizzaType', on_delete=models.PROTECT)
toppings = models.ManyToManyField('Topping', blank=True)
special = models.BooleanField()
price = models.DecimalField(
    max_digits=4, decimal_places=2, editable=False, default=0
)

def calculate_price(self, topping_amount):
    print(self.toppings.count())
    topping_amount = self.toppings.count()
    base_pizza = PizzaBase.objects.get(
        portion_size=self.portion_size, pizza_type=self.pizza_type,
        special=self.special, topping_amount=topping_amount
    )
    self.price = base_pizza.price

def save(self, *args, **kwargs):
    super().save(*args, **kwargs)
    self.calculate_price()

This is model I've defined for Django and I'm trying to set the the price of the pizza that is being created when the user saves form, but every time the code is run, the toppings.count value is always behind.

For instance, if I pick three toppings, and before saving the form in the admin panel there were only two toppings selected, I'd get the calculated price for two toppings. I've tried changing the order of the save method but it didn't change anything. I've also used the shell to check if there was a problem, but while in Django shell everything was fine with the toppings count. I've also check the admin interface, refreshed it multiple times, cleared cache and everything seemed fine there too.

I've started Signals to solve this. Creating a receiver for a post_save() signal, but haven't fully tested it yet.

Does anyone know what might be happening? I'm running this code locally, using SQLite, the app is still under development and I'm only using VSCode, nothing else.


Solution

  • The answer to this question is here: https://docs.djangoproject.com/en/3.0/ref/signals/#m2m-changed

    Many-to-many relationships are saved after the model is saved. So I built a signal to solve this.

    Thanks for the help!