2016-08-28 48 views
1

兩種情況:peewee自定義字段 - 定義允許的值

1.)我想定義一個只能取整數0,1或2的屬性(val)。

class Trinary(Model): 
    """val should accept the values 0, 1 or 2 only""" 
    val = IntegerField() 

2.)我想定義屬性(VAL),只能採取特定字符串,例如[ 「草莓」, 「桃」, 「蘋果」]

class Fruit(Model): 
    """val should accept the values "strawberry", "peach" or "apple" only """ 
    val = ??? 

使用peewee可以實現這樣的限制嗎?

感謝您的幫助!

莫夫

回答

1

目的IntegerField等是類,可以被子類(documentation):

應該定義db_value的類從蟒轉換爲數據庫, 和python_value爲反過來

class TrinaryField(IntegerField): 
     def db_value(self, value): 
      if value not in [0,1,2]: 
       raise TypeError("Non-trinary digit") 
      return super().db_field(value) # call