我目前正在使用 Python-Graphene 为我的 Django 应用程序创建一个 GraphQL 接口(interface)。虽然查询效果很好,但突变 - 不完全。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
}
}
运行它会返回正确的对象并且
ok
是 True
,但没有数据被推送到数据库。我应该怎么办?我错过了什么? 最佳答案
关闭...在您的 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)
关于python - Django/Graphene 突变不适用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49379099/