Python: if more than one of three things is true, return false

前端 未结 11 2539
温柔的废话
温柔的废话 2021-02-14 01:33

I\'m writing a django model that allows my site to have coupons.

Coupons can have three types: lifetime account voucher, certain period of months voucher, certain numb

11条回答
  •  心在旅途
    2021-02-14 01:53

    One thing I've done in similar situations is this:

    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")  
    

    It's now much easier to add new coupon types to check for in the future!

提交回复
热议问题