我正在尝试创建一个 graphql 突变,我无法将 categoryNode 作为输入字段添加到 AddEquipment 突变

I am trying to create a graphql mutation , where i cannot add the categoryNode as a input feild to AddEquipment mutation

类别模型 这是我的类别模型

class Category(models.Model):
    _id = models.ObjectIdField(primary_key=True)
    name = models.CharField(max_length=100)

类别节点 我使用 relay

创建了一个类别节点
class CategoryNode(DjangoObjectType):
    class Meta:
        model = Category
        filter_fields = ['name', 'equipments']
        interfaces = (relay.Node,)

添加装备变异 而突变我需要在突变输入中向设备对象添加一个类别对象

class AddEquipment(relay.ClientIDMutation):
    class Input:
        name = graphene.String(required=True)
        category = graphene.Field(CategoryNode)

    equipment = graphene.Field(EquipmentNode)

    @classmethod
    def mutate_and_get_payload(cls, root, info, **inputs):
        equipment_instance = Equipment(
            name=inputs.get('name'),
            category=inputs.get('category')
        )
        equipment_instance.save()
        return AddEquipment(equipment=equipment_instance)

通过这段代码我得到了这样的错误

"AssertionError: AddEquipmentInput.category field type must be Input Type but got: CategoryNode."

很遗憾,您不能这样做,因为 ObjectType 不能是 InputObjectType。使它工作的唯一方法是创建一个新的 class 派生自 InputObjectType.

class CategoryInput(graphene.InputObjectType):
    id = graphene.ID(required=True)
    name = graphene.String()

并使用它。

class AddEquipment(relay.ClientIDMutation):
    class Input:
        name = graphene.String(required=True)
        category = graphene.Field(CategoryInput, required=True)

    ...

UPDATE

我认为在你的情况下,如果你只想获取类别实例,那么在你的突变中输入类别的全部细节是没有意义的,所以我建议只输入 name 和类别id 在你的内部 class Input 并在你的 mutate_and_get_payload.

中查询类别实例 see example

准确地说,您应该将代码重构为:

class AddEquipment(relay.ClientIDMutation):
    class Input:
        name = graphene.String(required=True)
        category_id = graphene.ID(required=True)

    equipment = graphene.Field(EquipmentNode)

    @classmethod
    def mutate_and_get_payload(cls, root, info, **inputs):
        # if ID is global make sure to extract the int type id.
        # but in this case we assume that you pass an int.
        category_instance = Category.objects.get(id=inputs.get('category_id'))
        equipment_instance = Equipment(
            name=inputs.get('name'),
            category=category_instance
        )
        equipment_instance.save()
        return AddEquipment(equipment=equipment_instance)