简体   繁体   English

如何覆盖peewee字段中的“setter”?

[英]How to overwrite “setter” in peewee field?

Given the following code, I would like to modify EnumField in a way that I can pass strings into the MyClass constructor and they are autocasted to enum right away.鉴于以下代码,我想以一种可以将字符串传递给MyClass构造函数的方式修改EnumField ,并且它们会立即自动转换为 enum 。 I thought of overwriting the "setter", but couldn't find it in peewee's code.我想覆盖“setter”,但在peewee的代码中找不到它。

from enum import Enum
from peewee import CharField, Model


class EnumField(CharField):
    "Custom field to support enums"

    def __init__(self, enum, **kwargs):
        super(EnumField, self).__init__(**kwargs)
        self.enum = enum

    def db_value(self, value):
        if isinstance(value, Enum):
            return str(value.name)  # convert enum to str
        elif isinstance(value, basestring):
            return value
        return None

    def python_value(self, value):
        if value:
            return self.enum[value]  # convert str to enum
        return None

    def clone_base(self, **kwargs):
        return super(EnumField, self).clone_base(enum=self.enum, **kwargs)


class FooEnum(Enum):
    FOO = "foo"
    BAR = "bar"


class MyClass(Model):
    field1 = EnumField(FooEnum)


my_class = MyClass(field1='foo')
type(my_class.field1) == FooEnum  # False, it's str but I would like it to be autocasted

my_class.save()
my_class = MyClass.get()
type(my_class.field1) == FooEnum  # True

According to the Peewee docs for fields it looks like the method you are missing is coerce :根据字段Peewee 文档,您缺少的方法似乎是coerce

coerce(value)强制(值)

This method is a shorthand that is used, by default, by both db_value and python_value.此方法是默认情况下由 db_value 和 python_value 使用的速记。 You can usually get away with just implementing this.您通常可以通过实现这一点而逃脱惩罚。

 Parameters: value – arbitrary data from app or backend Return type: python data type

I would make coerce be the same as python_value :我会让coercepython_value相同:

def python_value(self, value):
    if value:
        return self.enum[value]  # convert str to enum
    return None
coerce = python_value

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM