M
M
MalekBV2020-06-22 17:32:20
Django
MalekBV, 2020-06-22 17:32:20

Django. Price is not saved on save() method?

There is a model:

class ProductSet(models.Model):
    """Set of some products"""
    price = models.DecimalField(max_digits=7, decimal_places=2, blank=True, null=True)
    set_products = models.ManyToManyField(SetProduct, related_name='set', verbose_name='Товары набора')

    def save(self, *args, **kwargs):
        """If a total price for that product set isn't defined,
        save it as a sum of the set products total_price
        """
        if not self.price:
            super().save(*args, **kwargs)
            self.price = sum([set_product.total_price for set_product in self.set_products.all()])

        super().save(*args, **kwargs)


The first call to save is to save the "set_products" many-to-many relationship. The second save statement to save the new self.price. But it doesn't work, the price was only saved after I double clicked the save button of the django admin. What is the reason and how can I solve it?

PS SetProduct:

class SetProduct(models.Model):
    """Product in ProductSet"""
    product = models.ForeignKey(Product, on_delete=models.CASCADE, verbose_name='Товар', related_name='product_sets')
    count = models.PositiveSmallIntegerField('Количество', default=1)
    actual_price = models.DecimalField('Актуальная цена', max_digits=7, decimal_places=2, blank=True, null=True)

    def save(self, *args, **kwargs):
        """If an actual price isn't defined, set it as the product.price_with_discount"""
        if not self.actual_price:
            self.actual_price = self.product.price_with_discount

        super().save(*args, **kwargs)

    @property
    def total_price(self):
        return self.actual_price * self.count

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Tikhonov, 2020-06-22
@malekBV

M2M fields are filled in by the admin only after exiting save(), super() won't help here. Look towards signal processing m2m_changed.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question