我正在写一个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") 我知道有一种更好的方法可以做到这一点,但我没有看到它(称之为编码器的块)。
非常感谢您的帮助。
如果重要的话,这三种类型是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)发布于 2011-07-14 10:33:34
我在类似的情况下做过的一件事是:
coupon_types = (self.months, self.dollars, self.lifetime,)
true_count = sum(1 for ct in coupon_types if ct)
if true_count > 1:
raise ValueError("Coupon can be valid for only one of: months, lifetime, or dollars") 现在更容易添加新的优惠券类型,以便在未来检查!
发布于 2011-07-14 09:55:15
您还可以使用list comp来过滤false值:
if len([x for x in [self.months, self.dollars, self.lifetime] if x]) > 1:
raise ValueError()或者在MRAB's answer上构建
if sum(map(bool, [self.months, self.dollars, self.lifetime])) > 1:
raise ValueErrro()发布于 2011-07-14 09:41:37
if (self.months && (self.dollars || self.lifetime)) || (self.dollars && (self.months || self.lifetime)) || (self.lifetime && (self.dollars || self.months))
raise ValueError("Coupon can be valid for only one of: months, lifetime, or dollars") 编辑:
我用卡诺图(http://en.wikipedia.org/wiki/Karnaugh_map)做了一个快速的电路模拟。最后,这是一个最小的布尔逻辑函数:
if((self.months && self.dollars) || (self.dollars && self.lifetime) || (self.lifetime && self.months))
raise ValueError("Coupon can be valid for only one of: months, lifetime, or dollars") 从逻辑上讲,我的两个语句都是等价的,但第二个语句在技术上更快/更有效。
编辑#2:如果有人感兴趣,这里是K图
A | B | C | f(A, B, C)
----------------------
0 | 0 | 0 | 0
----------------------
0 | 0 | 1 | 0
----------------------
0 | 1 | 0 | 0
----------------------
0 | 1 | 1 | 1
----------------------
1 | 0 | 0 | 0
----------------------
1 | 0 | 1 | 1
----------------------
1 | 1 | 0 | 1
----------------------
1 | 1 | 1 | 1这将简化为:
C\AB
-----------------
| 0 | 0 | 1 | 0 |
----------------- OR AB + BC + AC
| 0 | 1 | 1 | 1 |
-----------------https://stackoverflow.com/questions/6687557
复制相似问题