Skip to content

Commit 0544f81

Browse files
metheorytjnak
authored andcommitted
Add support for Python enums in sqlalchemy_utils.ChoiceType (#240)
1 parent 8ea2086 commit 0544f81

File tree

2 files changed

+34
-1
lines changed

2 files changed

+34
-1
lines changed

graphene_sqlalchemy/converter.py

+8-1
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
from enum import EnumMeta
2+
13
from singledispatch import singledispatch
24
from sqlalchemy import types
35
from sqlalchemy.dialects import postgresql
@@ -163,7 +165,12 @@ def convert_enum_to_enum(type, column, registry=None):
163165
@convert_sqlalchemy_type.register(ChoiceType)
164166
def convert_choice_to_enum(type, column, registry=None):
165167
name = "{}_{}".format(column.table.name, column.name).upper()
166-
return Enum(name, type.choices)
168+
if isinstance(type.choices, EnumMeta):
169+
# type.choices may be Enum/IntEnum, in ChoiceType both presented as EnumMeta
170+
# do not use from_enum here because we can have more than one enum column in table
171+
return Enum(name, list((v.name, v.value) for v in type.choices))
172+
else:
173+
return Enum(name, type.choices)
167174

168175

169176
@convert_sqlalchemy_type.register(ScalarListType)

graphene_sqlalchemy/tests/test_converter.py

+26
Original file line numberDiff line numberDiff line change
@@ -145,6 +145,32 @@ def test_should_choice_convert_enum():
145145
assert graphene_type._meta.enum.__members__["en"].value == "English"
146146

147147

148+
def test_should_enum_choice_convert_enum():
149+
class TestEnum(enum.Enum):
150+
es = u"Spanish"
151+
en = u"English"
152+
153+
field = get_field(ChoiceType(TestEnum, impl=types.String()))
154+
graphene_type = field.type
155+
assert issubclass(graphene_type, graphene.Enum)
156+
assert graphene_type._meta.name == "MODEL_COLUMN"
157+
assert graphene_type._meta.enum.__members__["es"].value == "Spanish"
158+
assert graphene_type._meta.enum.__members__["en"].value == "English"
159+
160+
161+
def test_should_intenum_choice_convert_enum():
162+
class TestEnum(enum.IntEnum):
163+
one = 1
164+
two = 2
165+
166+
field = get_field(ChoiceType(TestEnum, impl=types.String()))
167+
graphene_type = field.type
168+
assert issubclass(graphene_type, graphene.Enum)
169+
assert graphene_type._meta.name == "MODEL_COLUMN"
170+
assert graphene_type._meta.enum.__members__["one"].value == 1
171+
assert graphene_type._meta.enum.__members__["two"].value == 2
172+
173+
148174
def test_should_columproperty_convert():
149175
field = get_field_from_column(column_property(
150176
select([func.sum(func.cast(id, types.Integer))]).where(id == 1)

0 commit comments

Comments
 (0)