不创建新类时Graphene枚举无法正常工作问题排查
问题原因及解决方案
核心原因
你使用的Graphene 2.1.8版本不支持在InputObjectType字段定义中直接动态创建Enum实例(即graph_type = Enum('GraphTypeEnum', GRAPH_TYPES)这种写法),框架无法识别并注册这个动态生成的枚举类型,导致graph_type字段在GraphiQL中缺失。
修复方案
需要先显式定义枚举类型(或提前将动态生成的Enum赋值给变量),再关联到输入对象的字段:
方式1:显式定义枚举类
from graphene import Enum, InputObjectType GRAPH_TYPES = [ ('step', 'Step graph'), ('bar', 'Bar graph'), ('line', 'Line graph'), ('dot', 'Dot graph'), ] class DataType(Enum): VELOCITY = 'velocity' ACCELERATION = 'acceleration' # 修正拼写错误:原代码为"accelration" class GraphType(Enum): step = 'Step graph' bar = 'Bar graph' line = 'Line graph' dot = 'Dot graph' class SomeInput(InputObjectType): data_type = DataType() graph_type = GraphType()
方式2:动态生成并提前赋值
from graphene import Enum, InputObjectType GRAPH_TYPES = [ ('step', 'Step graph'), ('bar', 'Bar graph'), ('line', 'Line graph'), ('dot', 'Dot graph'), ] class DataType(Enum): VELOCITY = 'velocity' ACCELERATION = 'acceleration' # 修正拼写错误 # 先将动态生成的Enum赋值给变量 GraphType = Enum('GraphTypeEnum', GRAPH_TYPES) class SomeInput(InputObjectType): data_type = DataType() graph_type = GraphType()
补充说明
- Graphene 3.x版本对动态枚举的支持更灵活,但你当前使用的2.x版本必须遵循“先定义/赋值枚举类型,再关联字段”的规则。
- 原代码中
ACCELERATION的值拼写错误(accelration→acceleration),建议同步修正,避免后续业务逻辑出错。
内容的提问来源于stack exchange,提问作者mah
相关产品推荐
相关产品推荐

