两种情况:
1.) 我想定义一个只能接受整数 0、1 或 2 的属性 (val)。
class Trinary(Model):
"""val should accept the values 0, 1 or 2 only"""
val = IntegerField()
2.) 我想定义一个只能接受特定字符串的属性 (val),例如 ["strawberry", "peach", "apple"]
class Fruit(Model):
"""val should accept the values "strawberry", "peach" or "apple" only """
val = ???
是否可以使用 peewee 实现此类限制?
感谢您的帮助!
手袋
最佳答案
对象 IntegerField
等是类,可以被子类化 ( documentation ):
这些类应该定义 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
关于python - peewee 自定义字段 - 定义允许值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39195189/