1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

graphene-djangoでのenum.Enumの扱い

Last updated at Posted at 2019-03-14

djangoでmodelを書いていてchoiceFieldでは普通enumを用いる。

これをmutationなどの引数にしたいとする。

通常以下の様にgraphene.Enumを用いる事になるが、
graphene-djangoはpythonのenumをgraphene.enumを書かずに自動で変換してくれる。

import graphene

class BarEnum(graphene.Enum):
    RED = 1
    GREEN = 2
    BLUE = 3

graphene-djangoでのEnumsの説明

このgrapheneのEnumsの説明ではpythonのEnum.enumは次のように使えるとなっている。

mutation.py

import enum

# pythonのenum
class BarEnum(enum.Enum):
    RED = 1
    GREEN = 2
    BLUE = 3

class CreateFoo(graphene.Mutation):
    Foo = graphene.Field(FooType)

    class Arguments:
        bar = graphene.Enum.from_enum(BarEnum)
    
    def mutate(self, info, **kwargs):
        pass

だがこれだと以下のエラーが出る。

ValueError: Unknown argument "bar"

正しくは以下

class CreateFoo(graphene.Mutation):
    Foo = graphene.Field(FooType)

    class Arguments:
        bar = graphene.Enum.from_enum(BarEnum)(required=True)
    

また、二つ同じenumを変換するとエラーとなる。

AssertionError: Found different types with the same name in the schema: FooEnum, FooEnum.

これを回避するには

class EnumInput():
    Foo = graphene.Enum.from_enum(FooEnum)


class AInput(graphene.InputObjectType):
    foo = EnumInput.Foo(required=True)
    baz = graphene.String(required=False)


class BInput(graphene.InputObjectType):
    foo = EnumInput.Foo(required=True)
    baz = graphene.Int(required=False)


class CreateFoo(graphene.Mutation):
    bar = graphene.Field(BarType)

    class Arguments:
        a = graphene.Argument(AInput)
        b = graphene.Argument(BInput)

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?