Mutation in django graphene for model with foreign key and many to many relationship
I have 2 models in my django app, the first is Tags model and the second is Post model, the problem is when i try to use mutation for the Post model to add a post from the graphql it doesn't work but it works fine in the Tags model, also the Queries works fine when i try to get data from the database.
Here's my Code: model.py:
from django.db import models
from django.utils.translation import gettext as _
from django.conf import settings
from django.contrib.auth import get_user_model
User = get_user_model()
# Create your models here.
class Tag(models.Model):
name = models.CharField(_("Tag Name"), max_length=50, unique=True)
def __str__(self):
return self.name
class Post(models.Model):
title = models.CharField(_("Title"), max_length=50, unique=True)
slug = models.SlugField(_("Post Slug"), unique=True)
body = models.TextField(_("Post Content"))
createdAt = models.DateTimeField(auto_now_add=True)
updatedAt = models.DateTimeField(auto_now=True)
published = models.BooleanField(_("Published"), default=False)
author = models.ForeignKey(User, verbose_name=_("Author"), on_delete=models.CASCADE)
tags = models.ManyToManyField("Tag", verbose_name=_("Tags"), blank=True)
class Meta:
ordering = ['-createdAt']
def __str__(self):
return self.title
schema.py:
import graphene
from graphene_django import DjangoObjectType
from django.contrib.auth import get_user_model
from .models import Post, Tag
User = get_user_model()
class PostType(DjangoObjectType):
class Meta:
model = Post
class TagType(DjangoObjectType):
class Meta:
model = Tag
fields = ('id', 'name',)
class TagInput(graphene.InputObjectType):
name = graphene.String(required=True)
class CreatePostMutation(graphene.Mutation):
class Arguments:
title = graphene.String()
body = graphene.String()
published = graphene.Boolean()
author_id = graphene.ID()
tags = graphene.List(graphene.Int)
success = graphene.Boolean()
post = graphene.Field(PostType)
@classmethod
def mutate(cls, root, info, title, body, published, author_id, tags):
author = User.objects.get(pk=author_id)
post_instance = Post(
title=title,
body=body,
published=published,
author=author,
)
post_instance.save(commit=False)
if tags:
tag_objects = Tag.objects.filter(pk__in=tags)
post_instance.tags.set(tag_objects)
post_instance.save()
return CreatePostMutation(success=True, post=post_instance)
class CreateTagMutation(graphene.Mutation):
class Arguments:
name = graphene.String(required=True)
tag = graphene.Field(TagType)
@classmethod
def mutate(cls, root, info, name):
tag = Tag(name=name)
tag.save()
return CreateTagMutation(tag=tag)
class Mutation(graphene.ObjectType):
create_post = CreatePostMutation.Field()
create_tag = CreateTagMutation.Field()
schema = graphene.Schema(query=Query, mutation=Mutation)
Here's what it returns:
{
"data": {
"createPost": {
"post": null
}
}
}