I have defined the following custom type for 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.
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
? Currently, row.enum
correctly evaluates to Bar.baz
, but I would like to get 3, the value being written to the sql table. Is it possible to do this? Note that the EnumColumnType
, Bar
and Foo
are defined correctly since sqlalchemy correctly persists rows to the table.
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.
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.