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。
当我添加了大量的打印数据时,所有的输入数据都是正确的,但计算却不正确,我该如何解决?
代码的问题在这一行。
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()