我目前正在使用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
}
}
运行它会返回正确的对象,ok
为True
,但没有数据被推送到数据库。我该怎么办?我错过了什么?
答案 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)