M
M
MalekBV2020-05-27 23:26:12
Django
MalekBV, 2020-05-27 23:26:12

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)


When I enter percentages in the admin panel, without discount_price, everything is calculated correctly.
If I enter discount_price, without discount_percent, then for some reason the value in the model is always stored in percents as 0.
5ececdad058fe694716969.png
When I printed all the values ​​inside were correct for the calculation, and the result is 0
Help, what is the reason?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
G
galaxy, 2020-05-27
@galaxy

So two sticks is a whole division.

self.discount_percent = (self.discount_price / self.product.price) * 100

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question