【问题标题】:Retrieve the object ID in GraphQL在 GraphQL 中检索对象 ID
【发布时间】:2018-03-11 10:36:16
【问题描述】:

我想知道是否可以获得对象的“原始 id”作为查询的结果。每当我向服务器发出请求时,它都会返回节点“全局标识符”,例如 U29saWNpdGFjYW9UeXBlOjEzNTkxOA==

查询与此类似:

{
  allPatients(active: true) {
    edges {
      cursor
      node {
        id
        state
        name
      }
    }
  }

返回是:

{
  "data": {
      "edges": [
        {
          "cursor": "YXJyYXljb25uZWN0aW9uOjA=",
          "node": {
            "id": "U29saWNpdGFjYW9UeXBlOjEzNTkxOA==",
            "state": "ARI",
            "name": "Brad"
          }
        }
      ]
  }
}

如何在数据库级别获取对象的“原始”ID(例如“112”)而不是该节点唯一标识符?

ps.:我在服务器端使用graphene-python和Relay。

【问题讨论】:

    标签: python graphql graphene-python


    【解决方案1】:

    第一个选项,删除 relay.Node 作为你的 objectNode 声明的接口。

    第二个选项,使用自定义resolve_id函数返回id原值。

    例子

    class objectNode(djangoObjectType):
    
        .... Meta ....
    
        id = graphene.Int(source="id")
    
        def resolve_id("commons args ...."):
            return self.id
    

    希望对你有帮助

    【讨论】:

    • 我收到以下错误:Node.id expects type "ID!" but xxx.id provides type "Int".
    【解决方案2】:

    为我解决了在 Node 对象中覆盖默认 to_global_id 方法:

    class CustomNode(graphene.Node):
        class Meta:
            name = 'Node'
    
        @staticmethod
        def to_global_id(type, id):
            return id
    
    
     class ExampleType(DjangoObjectType):
         class Meta:
             model = Example
             interfaces = (CustomNode,)
    

    【讨论】:

      【解决方案3】:

      为了扩展最佳答案以及使用 SQLAlchemy 对象类型的人,这对我有用:

      class CustomNode(graphene.Node):
          class Meta:
              name = 'myNode'
      
          @staticmethod
          def to_global_id(type, id):
              return id
      
      class ExampleType(SQLAlchemyObjectType):
          class Meta:
              model = Example
              interfaces = (CustomNode, )
      

      如果您有其他使用 relay.Node 作为接口的 ObjectType,则需要在 CustomNode 下使用唯一名称。否则你会得到和断言错误。

      【讨论】:

      • 终于有人回答了这个问题而没有说定义一个单独的属性。这行得通,谢谢!
      【解决方案4】:

      这样你就可以检索数据库中的真实ID:

      def get_real_id(node_id: str):
          _, product_id_real = relay.Node.from_global_id(global_id=node_id)
          return product_id_real
      

      【讨论】:

        猜你喜欢
        • 2020-11-02
        • 1970-01-01
        • 2013-11-15
        • 2014-01-26
        • 2021-05-26
        • 2017-06-06
        • 2020-03-29
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多