Django / Graphene突变并不适用

时间:2018-03-20 08:06:41

标签: python django graphene-python

我目前正在使用Python-Graphene为我的Django应用程序创建GraphQL接口。虽然查询效果很好,但突变 - 并不完全。

Ingredient的模型:

class Ingredient(models.Model):
    name = models.CharField(max_length=255)
    slug = models.SlugField(editable=False)
    needs_refill = models.BooleanField(default=False)
    created = models.DateTimeField('created', auto_now_add=True)
    modified = models.DateTimeField('modified', auto_now=True)

    def __str__(self):
        return self.name

    def save(self, *args, **kwargs):
        self.slug = slugify(self.name)
        super(Ingredient, self).save(*args, **kwargs)

这里是架构代码(此处为完整代码:https://ctrlv.it/id/107369/1044410281):

class IngredientType(DjangoObjectType):
    class Meta:
        model = Ingredient

...

class CreateIngredient(Mutation):
    class Arguments:
        name = String()

    ok = Boolean()
    ingredient = Field(IngredientType)

    def mutate(self, info, name):
        ingredient = IngredientType(name=name)
        ok = True
        return CreateIngredient(ingredient=ingredient, ok=ok)


class MyMutations(ObjectType):
    create_ingredient = CreateIngredient.Field()


schema = Schema(query=Query, mutation=MyMutations)

和我的突变:

mutation {
  createIngredient(name:"Test") {
    ingredient {
      name
    }
    ok
  }
}

运行它会返回正确的对象,okTrue,但没有数据被推送到数据库。我该怎么办?我错过了什么?

1 个答案:

答案 0 :(得分:4)

关闭...在您的mutate方法中,您需要将您的素材保存为Ingredient(不是IngredientType)的实例,然后使用它来创建IngredientType宾语。另外,您应将mutate声明为@staticmethod。类似的东西:

    @staticmethod
    def mutate(root, info, name):
        ingredient = Ingredient.objects.create(name=name)
        ok = True
        return CreateIngredient(ingredient=ingredient, ok=ok)