Django/Graphene 突变不适用

Django/Graphene mutations doesn't apply

我目前正在使用 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
  }
}

运行 它 returns 正确的对象并且 okTrue,但是没有数据被推送到数据库。我应该怎么办?我错过了什么?

关闭...在您的 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)