[英]SQLAlchemy Get Raw SQL Value from TypeDecorator
I have defined the following custom type for sqlalchemy: 我为sqlalchemy定义了以下自定义类型:
class EnumColumnType(TypeDecorator):
impl = Integer
def __init__(self, enum, *args, **kwargs):
self.enum = enum
super(EnumColumnType, self).__init__(*args, **kwargs)
def process_bind_param(self, value, dialect):
if value is None:
return None
return value.value
def process_result_value(self, value, dialect):
if value is None:
return None
return self.enum(value)
@property
def python_type(self):
return int
Essentially, it encapsulates a python enum and writes it back as an integer to the sql table. 本质上,它封装了一个python枚举,并将其作为整数写回到sql表中。
Assume I have the following enum defined: 假设我定义了以下枚举:
class Bar(Enum):
foo = 1
bar = 2
baz = 3
Assume I have a model as follows: 假设我有一个模型,如下所示:
class Foo(base):
enum = Column(EnumColumnType(Bar))
id = Column(Integer, primary_key=True)
If I have an instance of Foo ie row = Foo(enum=Bar.baz)
, is it possible for me to get the sql type of row.enum
? 如果我有一个Foo的实例,即
row = Foo(enum=Bar.baz)
,是否可以获取row.enum
的sql类型? Currently, row.enum
correctly evaluates to Bar.baz
, but I would like to get 3, the value being written to the sql table. 当前,
row.enum
正确计算为Bar.baz
,但是我想得到3,该值被写入sql表。 Is it possible to do this? 是否有可能做到这一点? Note that the
EnumColumnType
, Bar
and Foo
are defined correctly since sqlalchemy correctly persists rows to the table. 注意,由于
EnumColumnType
正确地将行保留到表中,因此EnumColumnType
, Bar
和Foo
的定义正确。
I'm not an SQLAlchemy user, but I can say that the point of Enum
is to provide a textual representation of a unique value. 我不是SQLAlchemy用户,但是我可以说
Enum
是提供唯一值的文本表示形式。
From your description I think you would be best served by an IntEnum
which, while still having a textual representation of Bar.foo
or Bar.baz
would still be directly usable as the int
1
or 3
从您的描述中,我认为最好使用一个
IntEnum
,它虽然仍具有Bar.foo
或Bar.baz
的文本表示形式, Bar.foo
仍可以直接用作int
1
或3
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.