Created
June 21, 2016 18:39
-
-
Save silas/b63ea0dcb96d6492c5f503267f30fbd2 to your computer and use it in GitHub Desktop.
Enum type for SQLAlchemy
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
This work is licensed under the MIT License (https://opensource.org/licenses/MIT) | |
Example: | |
class Example(Model): | |
class Type(enum.Enum): | |
one = 1 | |
two = 2 | |
type = sa.Column(EnumType(Type), nullable=False) | |
""" | |
import sqlalchemy as sa | |
class EnumType(sa.TypeDecorator): | |
impl = sa.SmallInteger | |
def __init__(self, data, **kw): | |
self.data = data | |
super(EnumType, self).__init__(**kw) | |
def process_bind_param(self, value, dialect): | |
if value is None: | |
return value | |
return value.value | |
def process_result_value(self, value, dialect): | |
return self.data(value) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment