Django integration for Graphene enabling GraphQL APIs in Django applications
npx @tessl/cli install tessl/pypi-graphene-django@2.16.0A Django integration for Graphene that enables developers to build GraphQL APIs in Django applications. Graphene Django provides seamless integration between Django's ORM and GraphQL schema definition through automatic model-to-GraphQL type conversion, built-in support for Django model relationships and filtering, comprehensive GraphQL view classes with configurable GraphiQL interface, and advanced features like relay-style pagination and Django REST framework integration.
pip install "graphene-django>=2.0"from graphene_django import DjangoObjectType, DjangoListField, DjangoConnectionFieldCommon import patterns:
# Main types
from graphene_django import DjangoObjectType
# Fields for schema definition
from graphene_django.fields import DjangoListField, DjangoConnectionField
# Views for Django integration
from graphene_django.views import GraphQLViewfrom django.db import models
from graphene_django import DjangoObjectType
import graphene
# Django model
class UserModel(models.Model):
name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100)
# GraphQL type from Django model
class User(DjangoObjectType):
class Meta:
model = UserModel
# GraphQL schema
class Query(graphene.ObjectType):
users = graphene.List(User)
def resolve_users(self, info):
return UserModel.objects.all()
schema = graphene.Schema(query=Query)
# Django URLs configuration
from django.urls import path
from graphene_django.views import GraphQLView
urlpatterns = [
path('graphql/', GraphQLView.as_view(graphiql=True)),
]Graphene Django follows a layered architecture:
This design enables maximum reusability across Django web applications requiring GraphQL APIs, with built-in support for Django's authentication system, middleware integration, and sophisticated GraphQL schemas that leverage Django's powerful ORM capabilities.
Main classes for converting Django models to GraphQL types with automatic field mapping, relationship support, and ORM integration.
class DjangoObjectType(graphene.ObjectType):
"""
Main class for creating GraphQL object types from Django models.
Meta Options:
- model: Django model to wrap
- fields: Fields to include ('__all__', list, or tuple)
- exclude: Fields to exclude (list or tuple)
- filter_fields: Fields available for filtering
- filterset_class: Custom filterset class
- connection: Connection class for pagination
"""
class DjangoObjectTypeOptions(ObjectTypeOptions):
"""Options class for DjangoObjectType meta configuration."""
class ErrorType(graphene.ObjectType):
"""Standard error type for form/serializer errors."""
field = graphene.String()
messages = graphene.List(graphene.String)
@classmethod
def from_errors(cls, errors):
"""Convert Django form errors to GraphQL format."""Specialized GraphQL fields for Django querysets with automatic resolution, pagination support, and ORM optimization.
class DjangoListField(graphene.Field):
"""Field for returning lists of Django objects with automatic queryset resolution."""
def __init__(self, _type, *args, **kwargs):
"""Initialize with Django object type."""
class DjangoConnectionField(graphene.relay.ConnectionField):
"""Relay-style connection field with Django-specific pagination."""
def __init__(self, type, on=None, max_limit=None, enforce_first_or_last=False, **kwargs):
"""
Initialize connection field.
Parameters:
- type: GraphQL type for connections
- on: Manager/related name to use
- max_limit: Maximum pagination limit
- enforce_first_or_last: Require first/last arguments
"""Django view classes for serving GraphQL endpoints with configurable GraphiQL interface, middleware support, and HTTP request handling.
class GraphQLView(django.views.generic.View):
"""Django view for serving GraphQL endpoint with GraphiQL support."""
def __init__(self, schema=None, executor=None, middleware=None,
graphiql=False, pretty=False, batch=False, **kwargs):
"""
Initialize GraphQL view.
Parameters:
- schema: GraphQL schema
- executor: Custom executor
- middleware: GraphQL middleware
- graphiql: Enable GraphiQL interface
- pretty: Pretty print JSON
- batch: Enable query batching
"""
class HttpError(Exception):
"""HTTP-specific exception for GraphQL errors."""Django-filter integration for advanced GraphQL field filtering with automatic filter generation and custom filter support.
class DjangoFilterConnectionField(DjangoConnectionField):
"""Connection field with django-filter integration."""
def __init__(self, type, fields=None, filterset_class=None,
extra_filter_meta=None, **kwargs):
"""
Initialize filter connection field.
Parameters:
- fields: Fields to filter on
- filterset_class: Custom FilterSet class
- extra_filter_meta: Additional FilterSet metadata
"""Form-based GraphQL mutations with Django form validation, error handling, and automatic input type generation.
class DjangoFormMutation(graphene.relay.ClientIDMutation):
"""Concrete form mutation with error handling."""
errors = graphene.List(ErrorType)
class Meta:
"""Meta options for form mutations."""
form_class = None
only_fields = None
exclude_fields = None
class DjangoModelFormMutation(DjangoFormMutation):
"""Model form-based mutations with CRUD operations."""Django REST Framework serializer integration for GraphQL mutations with comprehensive validation and model operations.
class SerializerMutation(graphene.relay.ClientIDMutation):
"""Mutation class using Django REST Framework serializers."""
errors = graphene.List(ErrorType)
class Meta:
"""Meta options for serializer mutations."""
serializer_class = None
model_operations = ['create', 'update']
lookup_field = 'id'Test case classes and utility functions for GraphQL testing in Django applications with assertion helpers and query execution.
class GraphQLTestCase(django.test.TestCase):
"""Test case base class for GraphQL testing."""
def graphql_query(query, variables=None, headers=None, client=None):
"""
Utility function for making GraphQL requests in tests.
Parameters:
- query: GraphQL query string
- variables: Query variables
- headers: HTTP headers
- client: Django test client
Returns:
Response object with GraphQL result
"""Development debugging tools for GraphQL queries with SQL query inspection, performance monitoring, and middleware integration.
class DjangoDebugMiddleware:
"""Middleware to capture SQL queries and timing information."""
class DjangoDebug(graphene.ObjectType):
"""Debug information container for GraphQL queries."""
sql = graphene.List(DjangoDebugSQL)
class DjangoDebugSQL(graphene.ObjectType):
"""Individual SQL query debug information."""
sql = graphene.String()
duration = graphene.Float()
vendor = graphene.String()
alias = graphene.String()
params = graphene.String()# Main package version
__version__ = "2.16.0"
# Core type conversion constants
ALL_FIELDS = "__all__"
# Mutation error handling
MUTATION_ERRORS_FLAG = "graphene_mutation_has_errors"