You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何获取Graphene中SQLAlchemyObjectType对应的GraphQL schema字符串?

解决方法

要获取Graphene生成的GraphQL schema字符串,可按以下步骤操作:

1. 组装Schema实例

将你定义的PostSchema注册到Graphene Schema对象中:

import graphene
# 导入你已定义的Post模型、PostSchema

class Query(graphene.ObjectType):
    # 可按需定义查询字段,此处只要注册PostSchema类型即可
    post = graphene.Field(PostSchema, id=graphene.Int())

schema = graphene.Schema(query=Query)

2. 提取SDL字符串

Graphene的Schema实例直接转为字符串即可得到完整的SDL(Schema Definition Language)内容:

# 获取完整schema字符串
full_sdl = str(schema)
print(full_sdl)

# 单独提取Post类型定义
post_type_def = [block for block in full_sdl.split("\n\n") if block.startswith("type Post")][0]
print(post_type_def)

3. 字段类型适配说明

你需求中time_created为Int类型,默认SQLAlchemy的DateTime字段会被Graphene映射为DateTime类型,可在PostSchema中显式覆盖字段定义:

class PostSchema(SQLAlchemyObjectType):
    time_created = graphene.Int(required=True)

    class Meta:
        model = Post
  • 你此前尝试访问的type_defs不属于Graphene的内置属性,该属性常见于其他GraphQL框架(如Apollo)。

内容的提问来源于stack exchange,提问作者Ali Husham

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 14:15:05