嵌套时解析器不接收参数

Resolver Not Receiving Arguments when Nested

我有一个 类 的列表存储在内存中,我试图通过各种类型进行解析。它是通过方法 get_inventory().

引用的

当我单独调用 类 时,它们会按照我的预期进行解析。

但是当我尝试将一个嵌套在另一个中时,值为 returning null。

代码,后面是一些例子:

class Account(graphene.ObjectType):

    account_name = graphene.String()
    account_id = graphene.String()

    def resolve_account(
        self, info,
        account_id=None,
        account_name=None
    ):

        inventory = get_inventory()

        result = [Account(
            account_id=i.account_id,
            account_name=i.account_name
        ) for i in inventory if (
            (i.account_id == account_id) or 
            (i.account_name == account_name)
        )]

        if len(result):
            return result[0]
        else:
            return Account()

account = graphene.Field(
    Account, 
    resolver=Account.resolve_account, 
    account_name=graphene.String(default_value=None),
    account_id=graphene.String(default_value=None)
)

class Item(graphene.ObjectType):

    item_name = graphene.String()
    region = graphene.String()
    account = account

    def resolve_item(
        self, info,
        item_name=None
    ):
        inventory = get_inventory()

        result = [Item(
            item_name=i.item_name,
            region=i.region,
            account=Account(
                account_id=i.account_id
            )
        ) for i in inventory if (
            (i.item_name == item_name)
        )]

        if len(result):
            return result[0]
        else:
            return Item()

item = graphene.Field(
    Item, 
    resolver=Item.resolve_item, 
    item_name=graphene.String(default_value=None)
)

class Query(graphene.ObjectType):
    account = account
    item = item

schema = graphene.Schema(query=Query)

假设我有一个帐户 foo,其中有一个项目 bar。以下查询 return 字段正确。

{
  account(accountName:"foo") {
    accountName
    accountId
  }
}

{
  item(itemName: "bar") {
    itemName
    region
  }
}

因此,如果我想找到包含项目 bar 的帐户,我想我可以查询 bar 并获得 foo。但它 return 的 account 字段为 null

{
  item(itemName: "bar") {
    itemName
    region
    account {
      accountId
      accountName
    }
  }
}

回想一下,作为 resolve_item 的一部分,我正在做 account=Account(account_id=i.account_id) - 我希望它能起作用。

如果我将 resolve_account 的最后一个 return 语句更改为以下内容,accountId 总是 returns yo.

...
else:
    return Account(
        account_id='yo'
    )

所以这告诉我我的解析器正在触发,但是 resolve_item 中的调用没有正确传递 account_id

我做错了什么?

这是因为字段上的参数仅对其直接子项可用。如果您需要检索嵌套元素中的参数,您的顶级解析器需要 return 将参数作为源的一部分,并且您的嵌套元素现在可以从源对象访问它的参数。

据我所见,account_id 似乎已经作为 account 的一部分存储在 ObjectType 中,而不是作为参数传入。

所以如果我添加以下内容,我可以获得我想要的结果。

account_id = account_id if getattr(self, "account", None) is None else self.account.account_id