我在Django的保存方法中得到了错误的计算结果

问题描述 投票:0回答:1
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)

当我在管理面板上写 discount_percent 没有 discount_price 的计算就会正确。我得到的确实是一个折扣价格。但是当我写 discount_price 没有 discount_percent 时,Discount_percent 的值总是为 0。Screen from the admin

当我添加了大量的打印数据时,所有的输入数据都是正确的,但计算却不正确,我该如何解决?

python django
1个回答
2
投票

代码的问题在这一行。

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

在这一行中,你使用的是楼层除法。你需要使用普通的除法。例如3/5=0和100/105=0。任何时候左边的数字都比右边的大,因为它是浮动的,它将等于0。

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

计算结果应该是这样的: (35) * 100 = 60. 0如果需要一个整数,你可以直接用 int()

© www.soinside.com 2019 - 2024. All rights reserved.