0

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

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

类别节点 我使用中继创建了一个类别节点

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 字段类型必须是 Input Type 但得到:CategoryNode。”

4

1 回答 1

0

不幸的是,您不能这样做,因为 anObjectType不能是InputObjectType. 让它工作的唯一方法是创建一个从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)

    ...

更新

我认为在您的情况下,如果您只想获取类别实例,那么在您的突变中输入类别的完整详细信息是没有意义的,所以我建议只在您的内部输入name类别并查询类别实例,请参见在你的.idclass Inputmutate_and_get_payload

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

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)
于 2019-10-21T12:54:39.033 回答