升级graphene-django至v3遇类型错误:Int无法表示非整数值
解决方案
可以通过后端适配解决这个问题,无需修改前端代码,以下是几种可行的实现方式:
1. 自定义可自动转换字符串的Int标量
继承graphene的默认Int标量,重写其强制转换逻辑,让它能接受数字格式的字符串并转为整数:
from graphene import Int class CoercingInt(Int): @staticmethod def coerce_int(value): # 处理字符串类型的数字 if isinstance(value, str) and value.strip().isdigit(): return int(value.strip()) # 保留原有的Int类型处理逻辑 try: return int(value) except (ValueError, TypeError): return None # 在定义GraphQL参数时使用这个自定义标量 class YourQuery(graphene.ObjectType): some_field = graphene.Field(YourType, height=CoercingInt(required=True)) def resolve_some_field(self, info, height): # 这里的height已经是整数类型 return YourModel.objects.filter(height=height).first()
2. 全局请求中间件统一处理变量
编写GraphQL中间件,在请求进入解析阶段前,遍历所有变量,将符合数字格式的字符串转为对应数值类型:
from graphene_django.views import GraphQLView class StringToNumberMiddleware: def resolve(self, next, root, info, **args): # 处理查询变量 if hasattr(info.context, 'variables'): variables = info.context.variables for key, value in variables.items(): # 处理整数格式的字符串 if isinstance(value, str) and value.strip().isdigit(): variables[key] = int(value.strip()) # 可选:处理浮点数格式的字符串 elif isinstance(value, str): try: variables[key] = float(value.strip()) except ValueError: pass return next(root, info, **args) # 在配置GraphQL视图时添加中间件 urlpatterns = [ path('graphql', GraphQLView.as_view( schema=schema, middleware=[StringToNumberMiddleware()] )), ]
3. 单个字段解析时手动转换(适合少量字段场景)
如果只有少数几个字段需要处理,可以在字段的resolve方法里手动转换参数:
class YourQuery(graphene.ObjectType): some_field = graphene.Field(YourType, height=graphene.Int(required=True)) def resolve_some_field(self, info, height): # 手动转换字符串为整数 if isinstance(height, str) and height.strip().isdigit(): height = int(height.strip()) return YourModel.objects.filter(height=height).first()
注意:方案1和方案2是全局或批量处理的方式,推荐优先使用,避免重复代码;方案3适合字段较少的场景,灵活但扩展性差。
内容的提问来源于stack exchange,提问作者IgnatvsNovel
相关产品推荐
相关产品推荐

