如何使用GrapheneDjango继电器中的外键关系更新模型?

2024-05-29 10:15:23 发布

您现在位置:Python中文网/ 问答频道 /正文

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

我创建的输入具有我应该在查询中传递的正确属性 但它不工作,并抛出下面显示的错误。 字段'id'需要一个数字,但得到了{'id':2}。

我无法理解这个错误背后的原因。我正在传递正确的输入(我相信) 有人能帮我理解为什么会这样吗

非常感谢您的建议和投入

输入:

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)

更新内容包括:

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)

客户端的变异查询:

mutation MyMutations {
    updateFuelSubtype(
        input: { 
            id: 2, 
            input: { label: "Updated 11 Mutation Label", 
                    fuelType: { id: 2 }
                }
                }
    ) {
        fuelSubtype {
            label
        }
    }
}

最终结果:

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

我还想指出,当我从查询中删除fuelType输入时,一切正常,例如:

mutation MyMutations {
    updateFuelSubtype(
        input: { 
            id: 2, 
            input: { label: "Updated 11 Mutation Label" }
                }
    ) {
        fuelSubtype {
            label
        }
    }
}

Tags: 模型idtruefieldinput错误oklabel
1条回答
网友
1楼 · 发布于 2024-05-29 10:15:23

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

mutation MyMutations {
    updateFuelSubtype(
        input: { 
            id: 2, 
            input: { label: "Updated 11 Mutation Label", 
                    fuelType: { id: 2 }
                }
                }
    ) {
        fuelSubtype {
            label
        }
    }
}

发送

mutation MyMutations {
    updateFuelSubtype(
        input: { 
            id: 2, 
            input: { label: "Updated 11 Mutation Label", 
                    fuelType: 2 # ## < - change
                }
                }
    ) {
        fuelSubtype {
            label
        }
    }
}

相关问题 更多 >

    热门问题