Skip to content

Instantly share code, notes, and snippets.

@mrowl
Created January 19, 2011 17:31
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mrowl/786501 to your computer and use it in GitHub Desktop.
Save mrowl/786501 to your computer and use it in GitHub Desktop.
This defines a new enum type using the sqlalchemy type decorator. Data is stored with the sqlalchemy SmallInteger type while strings are used with the model. Preferable to the varchar (too large) or native enum (pain on postgres).
import sqlalchemy as sa
class EnumIntType(sa.types.TypeDecorator):
impl = sa.types.SmallInteger
values = None
def __init__(self, values=None):
sa.types.TypeDecorator.__init__(self)
self.values = values
def process_bind_param(self, value, dialect):
return None if value == None else self.values.index(value)
def process_result_value(self, value, dialect):
return None if value == None else self.values[value]
@mrowl
Copy link
Author

mrowl commented Jan 19, 2011

Use is similar to the sqlalchemy Enum type:

sa.Column("type", EnumIntType(("one", "two", "three")), nullable=False)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment