我正在写一个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")
Run Code Online (Sandbox Code Playgroud)
我知道有更好的方法可以做到这一点,但我没有看到它(称之为编码器的块).
非常感谢帮助.
如果是maters,则三种类型是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)
Run Code Online (Sandbox Code Playgroud)
ran*_*let 10
我在类似情况下做过的一件事是:
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")
Run Code Online (Sandbox Code Playgroud)
现在更容易添加新的优惠券类型以便将来检查!
您还可以使用列表 comp 来过滤错误值:
if len([x for x in [self.months, self.dollars, self.lifetime] if x]) > 1:
raise ValueError()
Run Code Online (Sandbox Code Playgroud)
或者建立MRAB 的答案:
if sum(map(bool, [self.months, self.dollars, self.lifetime])) > 1:
raise ValueErrro()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3766 次 |
| 最近记录: |