Answer the question
In order to leave comments, you need to log in
Why is the value of a field in the model incorrectly considered by the save method in Django?
class Product(models.Model):
price = models.DecimalField('Цена', decimal_places=2, max_digits=9)
class Discount(models.Model):
product = models.OneToOneField(Product, on_delete=models.CASCADE, verbose_name='Товар', related_name='discount')
discount_price = models.DecimalField('Скидочная цена', decimal_places=2, max_digits=9, blank=True, null=True)
discount_percent = models.PositiveSmallIntegerField('Процент скидки (число)', blank=True, null=True)
def save(self, *args, **kwargs):
if not self.discount_percent and not self.discount_price:
raise ValueError('Заполните хотя бы одно поле: процент или скидочная цена')
if not self.discount_percent:
self.discount_percent = (self.discount_price // self.product.price) * 100
elif not self.discount_price:
self.discount_price = (self.product.price * self.discount_percent) // 100
super().save(*args, **kwargs)
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question