【发布时间】:2011-07-14 01:37:40
【问题描述】:
我正在编写一个 django 模型,它允许我的网站拥有优惠券。
优惠券可以有三种类型:终身帐户优惠券、一定期限的优惠券、一定数量的美元优惠券。
为简单起见,我只允许优惠券具有三个可能的值之一(即优惠券不能是 10 美元和 5 个月)。但我想检查何时保存优惠券以确保此规则为真。
目前我有:
true_count = 0
if self.months:
true_count += 1
if self.dollars:
true_count += 1
if self.lifetime:
true_count += 1
if true_count > 1:
raise ValueError("Coupon can be valid for only one of: months, lifetime, or dollars")
我知道有更好的方法可以做到这一点,但我没有看到(称之为 coder's block)。
非常感谢您的帮助。
如果它很重要,这三种类型是 int、int 和 bool
months = models.IntegerField(default=0)
cents = models.IntegerField(default=0)
#dollars = models.FloatField(default=0.00)
#dollars replaced with integer cents per advice of group
lifetime = models.BooleanField(default=False)
【问题讨论】:
-
问了 9 个深思熟虑的答案后 1 小时,这就是我喜欢 Stackoverflow 的原因