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