Retrieve the object ID in GraphQL
Asked Answered
E

4

7

I'd like to know whether it is possible to get the "original id" of an object as the result of the query. Whenever I make a request to the server, it returns the node "global identifier", something like U29saWNpdGFjYW9UeXBlOjEzNTkxOA== .

The query is similar to this one:

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

and the return is:

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

How can I get the "original" id of the object at the database level (e.g. '112') instead of that node unique identifier?

ps.: I am using graphene-python and Relay on the server side.

Eightfold answered 29/9, 2017 at 13:49 Comment(0)
T
6

Overriding default to_global_id method in Node object worked out for me:

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,)
Took answered 19/11, 2018 at 21:0 Comment(0)
M
3

First option, remove relay.Node as interface of your objectNode declaration.

Second option, use custom resolve_id fonction to return id original value.

Example

class objectNode(djangoObjectType):

    .... Meta ....

    id = graphene.Int(source="id")

    def resolve_id("commons args ...."):
        return self.id

Hope it helps

Milliner answered 29/6, 2018 at 13:11 Comment(1)
I got the following error: Node.id expects type "ID!" but xxx.id provides type "Int".Weatherwise
C
2

To expand on the top answer and for those using SQLAlchemy Object Types, this worked for me:

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, )

If you have other ObjectTypes using relay.Node as the interface, you will need to use a unique name under your CustomNode. Otherwise you will get and assertion error.

Chuchuah answered 9/3, 2020 at 21:6 Comment(1)
Finally someone that answers the question without saying to define a separate attribute. This works, thank you!Molder
G
2

With this you can retrive the real id in database:

def get_real_id(node_id: str):
    _, product_id_real = relay.Node.from_global_id(global_id=node_id)
    return product_id_real
Germanophile answered 10/7, 2020 at 19:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.