Django integration for Graphene enabling GraphQL APIs in Django applications
npx @tessl/cli install tessl/pypi-graphene-django@2.16.00
# Graphene Django
1
2
A 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.
3
4
## Package Information
5
6
- **Package Name**: graphene-django
7
- **Language**: Python
8
- **Installation**: `pip install "graphene-django>=2.0"`
9
10
## Core Imports
11
12
```python
13
from graphene_django import DjangoObjectType, DjangoListField, DjangoConnectionField
14
```
15
16
Common import patterns:
17
18
```python
19
# Main types
20
from graphene_django import DjangoObjectType
21
22
# Fields for schema definition
23
from graphene_django.fields import DjangoListField, DjangoConnectionField
24
25
# Views for Django integration
26
from graphene_django.views import GraphQLView
27
```
28
29
## Basic Usage
30
31
```python
32
from django.db import models
33
from graphene_django import DjangoObjectType
34
import graphene
35
36
# Django model
37
class UserModel(models.Model):
38
name = models.CharField(max_length=100)
39
last_name = models.CharField(max_length=100)
40
41
# GraphQL type from Django model
42
class User(DjangoObjectType):
43
class Meta:
44
model = UserModel
45
46
# GraphQL schema
47
class Query(graphene.ObjectType):
48
users = graphene.List(User)
49
50
def resolve_users(self, info):
51
return UserModel.objects.all()
52
53
schema = graphene.Schema(query=Query)
54
55
# Django URLs configuration
56
from django.urls import path
57
from graphene_django.views import GraphQLView
58
59
urlpatterns = [
60
path('graphql/', GraphQLView.as_view(graphiql=True)),
61
]
62
```
63
64
## Architecture
65
66
Graphene Django follows a layered architecture:
67
68
- **DjangoObjectType**: Converts Django models to GraphQL ObjectTypes with automatic field mapping
69
- **Registry**: Manages model-to-GraphQL type mappings and prevents duplicate registrations
70
- **Converter**: Handles Django field to GraphQL field conversion with support for all Django field types
71
- **Fields**: Provides specialized GraphQL fields (DjangoListField, DjangoConnectionField) for Django querysets
72
- **Views**: Django view classes that serve GraphQL endpoints with optional GraphiQL interface
73
- **Middleware**: Integration points for debugging, authentication, and request/response processing
74
75
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.
76
77
## Capabilities
78
79
### Core Types
80
81
Main classes for converting Django models to GraphQL types with automatic field mapping, relationship support, and ORM integration.
82
83
```python { .api }
84
class DjangoObjectType(graphene.ObjectType):
85
"""
86
Main class for creating GraphQL object types from Django models.
87
88
Meta Options:
89
- model: Django model to wrap
90
- fields: Fields to include ('__all__', list, or tuple)
91
- exclude: Fields to exclude (list or tuple)
92
- filter_fields: Fields available for filtering
93
- filterset_class: Custom filterset class
94
- connection: Connection class for pagination
95
"""
96
97
class DjangoObjectTypeOptions(ObjectTypeOptions):
98
"""Options class for DjangoObjectType meta configuration."""
99
100
class ErrorType(graphene.ObjectType):
101
"""Standard error type for form/serializer errors."""
102
field = graphene.String()
103
messages = graphene.List(graphene.String)
104
105
@classmethod
106
def from_errors(cls, errors):
107
"""Convert Django form errors to GraphQL format."""
108
```
109
110
[Core Types](./core-types.md)
111
112
### GraphQL Fields
113
114
Specialized GraphQL fields for Django querysets with automatic resolution, pagination support, and ORM optimization.
115
116
```python { .api }
117
class DjangoListField(graphene.Field):
118
"""Field for returning lists of Django objects with automatic queryset resolution."""
119
120
def __init__(self, _type, *args, **kwargs):
121
"""Initialize with Django object type."""
122
123
class DjangoConnectionField(graphene.relay.ConnectionField):
124
"""Relay-style connection field with Django-specific pagination."""
125
126
def __init__(self, type, on=None, max_limit=None, enforce_first_or_last=False, **kwargs):
127
"""
128
Initialize connection field.
129
130
Parameters:
131
- type: GraphQL type for connections
132
- on: Manager/related name to use
133
- max_limit: Maximum pagination limit
134
- enforce_first_or_last: Require first/last arguments
135
"""
136
```
137
138
[GraphQL Fields](./fields.md)
139
140
### Django Views
141
142
Django view classes for serving GraphQL endpoints with configurable GraphiQL interface, middleware support, and HTTP request handling.
143
144
```python { .api }
145
class GraphQLView(django.views.generic.View):
146
"""Django view for serving GraphQL endpoint with GraphiQL support."""
147
148
def __init__(self, schema=None, executor=None, middleware=None,
149
graphiql=False, pretty=False, batch=False, **kwargs):
150
"""
151
Initialize GraphQL view.
152
153
Parameters:
154
- schema: GraphQL schema
155
- executor: Custom executor
156
- middleware: GraphQL middleware
157
- graphiql: Enable GraphiQL interface
158
- pretty: Pretty print JSON
159
- batch: Enable query batching
160
"""
161
162
class HttpError(Exception):
163
"""HTTP-specific exception for GraphQL errors."""
164
```
165
166
[Django Views](./views.md)
167
168
### Filtering Integration
169
170
Django-filter integration for advanced GraphQL field filtering with automatic filter generation and custom filter support.
171
172
```python { .api }
173
class DjangoFilterConnectionField(DjangoConnectionField):
174
"""Connection field with django-filter integration."""
175
176
def __init__(self, type, fields=None, filterset_class=None,
177
extra_filter_meta=None, **kwargs):
178
"""
179
Initialize filter connection field.
180
181
Parameters:
182
- fields: Fields to filter on
183
- filterset_class: Custom FilterSet class
184
- extra_filter_meta: Additional FilterSet metadata
185
"""
186
```
187
188
[Filtering](./filtering.md)
189
190
### Forms Integration
191
192
Form-based GraphQL mutations with Django form validation, error handling, and automatic input type generation.
193
194
```python { .api }
195
class DjangoFormMutation(graphene.relay.ClientIDMutation):
196
"""Concrete form mutation with error handling."""
197
errors = graphene.List(ErrorType)
198
199
class Meta:
200
"""Meta options for form mutations."""
201
form_class = None
202
only_fields = None
203
exclude_fields = None
204
205
class DjangoModelFormMutation(DjangoFormMutation):
206
"""Model form-based mutations with CRUD operations."""
207
```
208
209
[Forms Integration](./forms.md)
210
211
### REST Framework Integration
212
213
Django REST Framework serializer integration for GraphQL mutations with comprehensive validation and model operations.
214
215
```python { .api }
216
class SerializerMutation(graphene.relay.ClientIDMutation):
217
"""Mutation class using Django REST Framework serializers."""
218
errors = graphene.List(ErrorType)
219
220
class Meta:
221
"""Meta options for serializer mutations."""
222
serializer_class = None
223
model_operations = ['create', 'update']
224
lookup_field = 'id'
225
```
226
227
[REST Framework Integration](./rest-framework.md)
228
229
### Testing Utilities
230
231
Test case classes and utility functions for GraphQL testing in Django applications with assertion helpers and query execution.
232
233
```python { .api }
234
class GraphQLTestCase(django.test.TestCase):
235
"""Test case base class for GraphQL testing."""
236
237
def graphql_query(query, variables=None, headers=None, client=None):
238
"""
239
Utility function for making GraphQL requests in tests.
240
241
Parameters:
242
- query: GraphQL query string
243
- variables: Query variables
244
- headers: HTTP headers
245
- client: Django test client
246
247
Returns:
248
Response object with GraphQL result
249
"""
250
```
251
252
[Testing Utilities](./testing.md)
253
254
### Debug Tools
255
256
Development debugging tools for GraphQL queries with SQL query inspection, performance monitoring, and middleware integration.
257
258
```python { .api }
259
class DjangoDebugMiddleware:
260
"""Middleware to capture SQL queries and timing information."""
261
262
class DjangoDebug(graphene.ObjectType):
263
"""Debug information container for GraphQL queries."""
264
sql = graphene.List(DjangoDebugSQL)
265
266
class DjangoDebugSQL(graphene.ObjectType):
267
"""Individual SQL query debug information."""
268
sql = graphene.String()
269
duration = graphene.Float()
270
vendor = graphene.String()
271
alias = graphene.String()
272
params = graphene.String()
273
```
274
275
[Debug Tools](./debug.md)
276
277
## Types
278
279
```python { .api }
280
# Main package version
281
__version__ = "2.16.0"
282
283
# Core type conversion constants
284
ALL_FIELDS = "__all__"
285
286
# Mutation error handling
287
MUTATION_ERRORS_FLAG = "graphene_mutation_has_errors"
288
```