Graphene Django Integration

3.2.3 · active · verified Sat Apr 11

Graphene Django provides an integration layer to build powerful GraphQL APIs on top of Django models and applications. It allows automatically mapping Django models to GraphQL types, handling connections, mutations, and more. Current version is 3.2.3, with new releases occurring frequently, often monthly or bi-monthly, supporting recent Django and Graphene versions.

Warnings

Install

Imports

Quickstart

This example shows how to expose a Django model through a GraphQL API using `graphene-django`. It defines a simple `Category` model, creates a `DjangoObjectType` for it, and exposes `all_categories` via a `DjangoConnectionField` for Relay-compliant pagination. It also demonstrates how to fetch a single category by ID. Remember to configure your Django `urls.py` with `GraphQLView` and add `graphene_django` to your `INSTALLED_APPS`.

import graphene
from graphene_django.types import DjangoObjectType
from graphene_django.fields import DjangoConnectionField
from django.db import models

# 1. Define a Django Model (e.g., in myapp/models.py)
class Category(models.Model):
    name = models.CharField(max_length=100)

    class Meta:
        # Essential for Relay Connection in Django 5+ to ensure consistent ordering
        ordering = ['name'] 

    def __str__(self):
        return self.name

# 2. Define a Graphene DjangoObjectType (e.g., in myapp/schema.py)
class CategoryType(DjangoObjectType):
    class Meta:
        model = Category
        # Explicitly list fields for clarity/control, or use '__all__'
        fields = ('id', 'name') 

# 3. Define a Query (e.g., in myapp/schema.py)
class Query(graphene.ObjectType):
    all_categories = DjangoConnectionField(CategoryType)

    # Optionally, resolve a single category by ID
    category = graphene.Field(CategoryType, id=graphene.ID())

    def resolve_category(root, info, id):
        try:
            return Category.objects.get(pk=id)
        except Category.DoesNotExist:
            return None

# 4. Create the Graphene Schema (e.g., in myapp/schema.py)
schema = graphene.Schema(query=Query)

# 5. Integrate into Django URLs (e.g., in project/urls.py)
# from django.urls import path
# from graphene_django.views import GraphQLView
# from myapp.schema import schema # Assuming myapp/schema.py
# urlpatterns = [
#     path('graphql/', GraphQLView.as_view(graphiql=True, schema=schema)),
# ]

# Remember to add 'graphene_django' to INSTALLED_APPS in your Django settings.py

view raw JSON →