嵌套时解析器不接收参数

时间:2018-11-26 18:53:03

标签: python graphql graphene-python

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

当我分别调用这些类时,它们会按我期望的方式解析。

但是当我尝试将另一个嵌套时,该值返回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。以下查询可正确返回字段。

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

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

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

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

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

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

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

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

我在做什么错了?

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

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

因此,如果我添加以下内容,就可以得到想要的结果。

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

相关问题