0
# Serializers
1
2
JSON:API compatible serializers that transform Django models into JSON:API resource objects with proper attributes, relationships, and resource identification. These serializers extend Django REST framework serializers with JSON:API specific functionality.
3
4
## Capabilities
5
6
### ModelSerializer
7
8
Enhanced ModelSerializer that automatically handles JSON:API resource object formatting, field name conversion, and relationship handling.
9
10
```python { .api }
11
class ModelSerializer(rest_framework.serializers.ModelSerializer):
12
"""
13
JSON:API compatible ModelSerializer with automatic resource object formatting.
14
15
Inherits all Django REST framework ModelSerializer functionality while adding:
16
- Automatic resource type detection from model
17
- JSON:API attribute and relationship formatting
18
- Support for sparse fieldsets via fields[type] query parameter
19
- Integration with JSON:API renderer for proper output format
20
"""
21
22
class Meta:
23
model = None # Django model class
24
fields = [] # List of fields to include
25
resource_name = None # Override resource type name
26
```
27
28
Usage example:
29
30
```python
31
from rest_framework_json_api import serializers
32
from myapp.models import Article
33
34
class ArticleSerializer(serializers.ModelSerializer):
35
class Meta:
36
model = Article
37
fields = ['title', 'content', 'author', 'created_at']
38
39
# Automatically generates JSON:API resource objects:
40
# {
41
# "type": "articles",
42
# "id": "1",
43
# "attributes": {
44
# "title": "Sample Article",
45
# "content": "Article content...",
46
# "created-at": "2023-01-01T12:00:00Z"
47
# },
48
# "relationships": {
49
# "author": {"data": {"type": "authors", "id": "5"}}
50
# }
51
# }
52
```
53
54
### HyperlinkedModelSerializer
55
56
Enhanced HyperlinkedModelSerializer with JSON:API hyperlink support in relationships and resource links.
57
58
```python { .api }
59
class HyperlinkedModelSerializer(rest_framework.serializers.HyperlinkedModelSerializer):
60
"""
61
JSON:API compatible HyperlinkedModelSerializer with hyperlinked relationships.
62
63
Extends HyperlinkedModelSerializer to generate proper JSON:API links in:
64
- Resource object links section
65
- Relationship links (self and related)
66
- Top-level links for collections
67
"""
68
69
class Meta:
70
model = None
71
fields = []
72
extra_kwargs = {} # Field-specific options
73
```
74
75
### ResourceIdentifierObjectSerializer
76
77
Serializer for JSON:API resource identifier objects used in relationships.
78
79
```python { .api }
80
class ResourceIdentifierObjectSerializer(BaseSerializer):
81
"""
82
Serializer for JSON:API resource identifier objects.
83
84
Handles resource identifier objects in the format:
85
{"type": "resource-type", "id": "123"}
86
87
Used internally by relationship fields.
88
"""
89
90
model_class = None # Model class this serializer represents
91
92
def __init__(self, model_class=None, *args, **kwargs):
93
"""
94
Initialize serializer with model class.
95
96
Args:
97
model_class: Django model class for this resource type
98
"""
99
100
def to_representation(self, instance):
101
"""
102
Convert model instance to resource identifier object.
103
104
Args:
105
instance: Django model instance
106
107
Returns:
108
dict: Resource identifier with type and id
109
"""
110
111
def to_internal_value(self, data):
112
"""
113
Convert resource identifier to model instance.
114
115
Args:
116
data: Resource identifier object dict
117
118
Returns:
119
Model instance
120
121
Raises:
122
ValidationError: If type doesn't match or object doesn't exist
123
"""
124
```
125
126
### SparseFieldsetsMixin
127
128
Mixin that adds support for JSON:API sparse fieldsets through the fields query parameter.
129
130
```python { .api }
131
class SparseFieldsetsMixin:
132
"""
133
Mixin for sparse fieldsets support via fields[type] query parameter.
134
135
Implements JSON:API sparse fieldsets specification:
136
https://jsonapi.org/format/#fetching-sparse-fieldsets
137
138
Usage: GET /articles?fields[articles]=title,author
139
"""
140
141
@property
142
def _readable_fields(self):
143
"""
144
Filter readable fields based on sparse fieldset query parameter.
145
146
Returns:
147
Filtered field list based on fields[resource-type] parameter
148
"""
149
```
150
151
Usage example:
152
153
```python
154
class ArticleSerializer(SparseFieldsetsMixin, serializers.ModelSerializer):
155
class Meta:
156
model = Article
157
fields = ['title', 'content', 'author', 'created_at']
158
159
# With request: GET /articles?fields[articles]=title,author
160
# Only returns title and author fields in attributes
161
```
162
163
### IncludedResourcesValidationMixin
164
165
Mixin that validates include parameter against serializer configuration.
166
167
```python { .api }
168
class IncludedResourcesValidationMixin:
169
"""
170
Mixin for validating include query parameter against serializer configuration.
171
172
Ensures that requested include paths are supported by the serializer's
173
included_serializers configuration.
174
175
Raises ParseError for unsupported include paths.
176
"""
177
```
178
179
### ReservedFieldNamesMixin
180
181
Mixin that prevents use of reserved field names.
182
183
```python { .api }
184
class ReservedFieldNamesMixin:
185
"""
186
Mixin that ensures reserved field names are not used in serializers.
187
188
Reserved field names include: 'meta', 'results', 'type', and others
189
that conflict with JSON:API specification.
190
191
Raises AssertionError if reserved field names are used.
192
"""
193
```
194
195
### PolymorphicModelSerializer
196
197
Serializer for polymorphic models that can represent multiple resource types.
198
199
```python { .api }
200
class PolymorphicModelSerializer(ModelSerializer):
201
"""
202
Serializer for polymorphic models supporting multiple resource types.
203
204
Handles models that represent different types of resources
205
(e.g., Animal model with Cat and Dog subtypes).
206
"""
207
208
def to_representation(self, instance):
209
"""
210
Convert instance to representation with correct resource type.
211
212
Args:
213
instance: Polymorphic model instance
214
215
Returns:
216
dict: Resource object with appropriate type
217
"""
218
219
def get_polymorphic_types(self):
220
"""
221
Get list of possible resource types for this serializer.
222
223
Returns:
224
list: Available resource type names
225
"""
226
```
227
228
## Field Name Formatting
229
230
All serializers support automatic field name formatting controlled by settings:
231
232
```python
233
# settings.py
234
JSON_API_FORMAT_FIELD_NAMES = True # Convert snake_case to kebab-case
235
236
# Model field: created_at -> JSON:API attribute: "created-at"
237
# Model field: author_id -> JSON:API attribute: "author-id"
238
```
239
240
## Error Handling
241
242
Serializers integrate with JSON:API error formatting:
243
244
```python
245
# Validation errors are automatically formatted as JSON:API errors:
246
# {
247
# "errors": [{
248
# "detail": "This field is required.",
249
# "source": {"pointer": "/data/attributes/title"},
250
# "status": "400"
251
# }]
252
# }
253
```
254
255
## Relationship Handling
256
257
Serializers automatically detect and handle relationships:
258
259
- ForeignKey fields become to-one relationships
260
- ManyToMany and reverse ForeignKey fields become to-many relationships
261
- Related fields are moved to relationships section
262
- Resource identifier objects are generated for relationship data
263
264
## Types
265
266
```python { .api }
267
# All Django REST framework serializer types are available
268
# Plus JSON:API specific classes above
269
270
from rest_framework.serializers import * # All DRF serializers re-exported
271
from rest_framework_json_api.serializers import (
272
ModelSerializer,
273
HyperlinkedModelSerializer,
274
ResourceIdentifierObjectSerializer,
275
SparseFieldsetsMixin,
276
PolymorphicModelSerializer
277
)
278
```