Reputation: 7935
I am currently creating a GraphQL interface for my Django app, using Python-Graphene. While queries works great, mutations - not quite.
The model for 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)
Here's the schema code (full code here: 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)
and my mutation:
mutation {
createIngredient(name:"Test") {
ingredient {
name
}
ok
}
}
Running it returns proper object and ok
is True
, but no data is pushed to the database. What should I do? What did I miss?
Upvotes: 3
Views: 2422
Reputation: 23512
Close...inside your mutate
method you need to save your ingredient as an instance of Ingredient
(not IngredientType
) and then use that to create your IngredientType
object. Also, you should declare mutate
as @staticmethod
. Something like:
@staticmethod
def mutate(root, info, name):
ingredient = Ingredient.objects.create(name=name)
ok = True
return CreateIngredient(ingredient=ingredient, ok=ok)
Upvotes: 4