Im fairly new to GraphQL and Graphene so it's hard for me to grasp whats wrong with my code. I can't even succeed with the simplest of the examples with GraphQL. Here is my code:
models.py
class Task(models.Model):
task_name = models.CharField('Aufgabe', max_length=255)
project = models.ForeignKey(Project, on_delete=models.CASCADE)
done = models.BooleanField(verbose_name="Erledigt", default=False)
def __str__(self):
return self.task_name
schema.py
class Task(models.Model):
task_name = models.CharField('Aufgabe', max_length=255)
project = models.ForeignKey(Project, on_delete=models.CASCADE)
done = models.BooleanField(verbose_name="Erledigt", default=False)
def __str__(self):
return self.task_name
My Query in the same file:
class TaskQuery(graphene.ObjectType):
all_tasks = graphene.List(TaskType)
def resolve_all_tasks(self, info, **kwargs):
return Task.objects.all()
Another Queryfunction:
class Query(graphene.ObjectType):
tasks = TaskQuery.all_tasks
projects = ProjectQuery.all_projects
This is my schema.py
int the settings directory:
import graphene
from todo import schema
class Query(schema.Query):
pass
class Mutation(schema.Mutation):
pass
schema = graphene.Schema(query=Query, mutation=Mutation)
When opening GraphiQL I can see the Query in the docs, but when I try to use this query like so (for example):
query {
tasks{
id
taskName
done
}
}
it always returns this:
{
"data": {
"tasks": null
}
}
Although I am pretty sure that I have entries in my Database that should be displayed there. I have checked the beginners Tutorial a view times and I can't even pass the first hurdle. Is there something I am missing?
So graphene relies heavily on types. I suggest making the following changes:
from graphene.relay import Node
from graphene import ObjectType, JSONField, String
from graphene_django import DjangoObjectType
from app.models import Task, Project
class TaskType(DjangoObjectType): # this is basically your nodes in the graph
class Meta:
filter_fields = {'id': ['exact']}
model = Task
interfaces = (Node,)
class ProjectType(DjangoObjectType): # FK should have a type as well
class Meta:
filter_fields = {'id': ['exact']}
model = Project
interfaces = (Node,)
class TasksQuery(ObjectType):
task = Node.Field(TaskType)
all_tasks = DjangoFilterConnectionField(TaskType)
In your schema.py make the following changes:
import graphene
from todo import schema
class Query(schema.TasksQuery):
pass
class Mutation(schema.Mutation):
pass
schema = graphene.Schema(query=Query, mutation=Mutation)
And then query using:
query {
allTasks {
id
taskName
done
}
}
Lemme know if this works.