【发布时间】:2021-01-21 09:24:14
【问题描述】:
我覆盖了 Django 的保存方法。在保存新的折扣项目时,会执行打印语句,但不会调用 update_discount 方法。我正在使用管理面板来保存折扣商品。我也想在 Django 更新方法上调用相同的 update_discount 方法。
代码:
class Discount(models.Model):
start_date = models.DateField(default=now)
end_date = models.DateField()
product = models.ForeignKey(Product, on_delete=models.CASCADE)
disc_per = models.PositiveIntegerField(default=None)
class Meta:
unique_together = ('start_date', 'end_date', 'product')
def __str__(self):
return str(self.start_date) + '-' + str(self.end_date) + '-' + str(self.product)
def save(self, *args, **kwargs):
print('saved.')
Discount.update_discount()
print('updated discount.')
super().save(*args, **kwargs)
@staticmethod
def update_discount():
discounts = Discount.get_all_discounts()
products = Product.get_all_products()
today = date.today()
# Reset discounted prices of all products
products.update(disc_price=None)
# Apply discount on products if today is sale
for discount in discounts:
product = Product.get_product_by_id(discount.product.id)
if (today >= discount.start_date) and (today <= discount.end_date):
per = discount.disc_per
price = discount.product.price
disc_price = Discount.cal_disc_price(per, price)
product.update(disc_price=disc_price)
else:
product.update(disc_price=None)
输出:
saved.
updated discount.
【问题讨论】:
-
尝试使用 self. self.update_discount()
-
@c.grey 我之前尝试过 self.update_discount() 。它没有用。
-
尝试在 update_discount 函数中打印一些东西。
-
调用了很多静态方法,但实现不共享。很难说哪里出了问题
-
为什么知道
update_discount方法没有被调用?
标签: django django-models django-3.0