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

peewee custom field - define allowed values

两种情况:

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 

从 peewee 3.0 实际方法 adapt() 可以将您的类型值转换为字段类型。

Imagine we have user status Enum with UserStatus

这样我们就可以将 Enum 转换为 int 并返回

#!/usr/bin/python3
from enum import IntEnum, unique

@unique
class UserStatus(IntEnum):
    active = 0
    blocked = 1
    deleted = 2

class UserStatusField(SmallIntegerField):
    def db_value(self, status_enum_field):
        """
        Python -> DataBase
        :param value: Enum
        :return: int
        """
        if not isinstance(status_enum_field, UserStatus):
            raise TypeError("Wrong type, must be enum")
        return super().adapt(status_enum_field.value)  # call

    def python_value(self, db_val):
        """
        DataBase -> Python
        :param db_val: int
        :return: Enum
        """
        return UserStatus(db_val)