首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何用Graphene-Django继电器中的外键关系更新模型?

如何用Graphene-Django继电器中的外键关系更新模型?
EN

Stack Overflow用户
提问于 2020-02-04 11:44:29
回答 1查看 708关注 0票数 2

我试图创建具有外键关系的模型的更新突变。我已经按照文档做了所有事情,但是当我提供外部模型输入时,它仍然不起作用。

我用应该在查询中传递的适当属性创建了输入,但是它不起作用,并抛出下面显示的错误。字段'id‘期望一个数字,但得到{'id':2}.

我无法理解这个错误背后的原因。我正在传递正确的输入(我相信)有人,请帮助我理解为什么会发生这种情况?

非常感谢您的建议和意见。

投入:

代码语言:javascript
复制
class FuelTypeInput(graphene.InputObjectType):
  # id of the FuelTypeModel
  id = graphene.Int()
  label = graphene.String()

class FuelSubtypeInput(graphene.InputObjectType):
  # Graphene ID
  id = graphene.ID()
  label = graphene.String()
  fuel_type = graphene.Field(FuelTypeInput)

更新突变:

代码语言:javascript
复制
class UpdateFuelSubType(relay.ClientIDMutation):
  class Input:
    id = Int() # id of the Fuel SubTypeModel
    input = FuelSubtypeInput(required=True)

  ok = True
  fuel_subtype = Field(FuelSubTypeNode)

  def mutate_and_get_payload(root, info, id, input):

    ok = False

    if FuelSubType.objects.filter(pk=id).update(**input):
      fuel_subtype = FuelSubType.objects.get(pk=id)
      ok = True

      return UpdateFuelSubType(fuel_subtype=fuel_subtype)

    return UpdateFuelSubType(fuel_subtype=None)

客户端的突变查询:

代码语言:javascript
复制
mutation MyMutations {
    updateFuelSubtype(
        input: { 
            id: 2, 
            input: { label: "Updated 11 Mutation Label", 
                    fuelType: { id: 2 }
                }
                }
    ) {
        fuelSubtype {
            label
        }
    }
}

最终结果:

代码语言:javascript
复制
{
  "errors": [
    {
      "message": "Field 'id' expected a number but got {'id': 2}.",
      "locations": [
        {
          "line": 48,
          "column": 5
        }
      ],
      "path": [
        "updateFuelSubtype"
      ]
    }
  ],
  "data": {
    "updateFuelSubtype": null
  }
}

我还想提到,当我从查询中删除fuelType输入时,一切都很好,例如:

代码语言:javascript
复制
mutation MyMutations {
    updateFuelSubtype(
        input: { 
            id: 2, 
            input: { label: "Updated 11 Mutation Label" }
                }
    ) {
        fuelSubtype {
            label
        }
    }
}
EN

回答 1

Stack Overflow用户

发布于 2021-04-05 13:40:13

只需在突变查询中发送外键的主键即可。而不是

代码语言:javascript
复制
mutation MyMutations {
    updateFuelSubtype(
        input: { 
            id: 2, 
            input: { label: "Updated 11 Mutation Label", 
                    fuelType: { id: 2 }
                }
                }
    ) {
        fuelSubtype {
            label
        }
    }
}

发送

代码语言:javascript
复制
mutation MyMutations {
    updateFuelSubtype(
        input: { 
            id: 2, 
            input: { label: "Updated 11 Mutation Label", 
                    fuelType: 2 # ## <--- change
                }
                }
    ) {
        fuelSubtype {
            label
        }
    }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60056700

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档