peewee 自定义字段 - 定义允许的值

Rag*_*fin 1 python python-3.x peewee

两种情况:

1.) 我想定义一个只能取整数 0、1 或 2 的属性 (val)。

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

2.) 我想定义一个只能接受特定字符串的属性 (val),例如 ["strawberry", "peach", "apple"]

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

是否可以使用 peewee 实现这样的限制?

谢谢你的帮助!

莫夫

Jam*_*s K 5

对象IntegerField等是类,可以被子类化(文档):

这些类应该定义db_value从 python 转换为数据库,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 
Run Code Online (Sandbox Code Playgroud)