import graphene
from graphene_django import DjangoObjectType
from blog.models import Post, Comment
class PostType(DjangoObjectType):
class Meta:
model = Post
fields = ('id', 'title', 'content', 'author', 'published_at')
class CommentType(DjangoObjectType):
class Meta:
model = Comment
fields = ('id', 'text', 'author', 'post', 'created_at')
class Query(graphene.ObjectType):
all_posts = graphene.List(PostType)
post = graphene.Field(PostType, id=graphene.Int())
def resolve_all_posts(self, info):
return Post.objects.filter(status='published')
def resolve_post(self, info, id):
return Post.objects.get(pk=id)
class CreatePost(graphene.Mutation):
class Arguments:
title = graphene.String(required=True)
content = graphene.String(required=True)
post = graphene.Field(PostType)
def mutate(self, info, title, content):
post = Post.objects.create(
title=title,
content=content,
author=info.context.user
)
return CreatePost(post=post)
class Mutation(graphene.ObjectType):
create_post = CreatePost.Field()
schema = graphene.Schema(query=Query, mutation=Mutation)
from django.urls import path
from graphene_django.views import GraphQLView
from .schema import schema
urlpatterns = [
path('graphql/', GraphQLView.as_view(graphiql=True, schema=schema)),
]
Graphene brings GraphQL to Django. I define types mapping to models and create resolvers for queries and mutations. Clients request exactly the data they need, reducing over-fetching. I use DjangoObjectType for automatic schema generation from models. For complex queries, custom resolvers fetch optimized data. GraphQL introspection provides automatic documentation. DataLoader prevents N+1 queries. For modern frontends or mobile apps, GraphQL offers flexibility traditional REST can't match. I expose GraphQL at /graphql endpoint.