Debian Codegraph @

docs/api-guide/relations.md

raw
1 ---
2 source:
3 - relations.py
4 ---
5
6 # Serializer relations
7
8 > Data structures, not algorithms, are central to programming.
9 >
10 > — [Rob Pike][cite]
11
12 Relational fields are used to represent model relationships. They can be applied to `ForeignKey`, `ManyToManyField` and `OneToOneField` relationships, as well as to reverse relationships, and custom relationships such as `GenericForeignKey`.
13
14 !!! note
15 The relational fields are declared in `relations.py`, but by convention you should import them from the `serializers` module, using `from rest_framework import serializers` and refer to fields as `serializers.<FieldName>`.
16
17 !!! note
18 REST Framework does not attempt to automatically optimize querysets passed to serializers in terms of `select_related` and `prefetch_related` since it would be too much magic. A serializer with a field spanning an ORM relation through its source attribute could require an additional database hit to fetch related objects from the database. It is the programmer's responsibility to optimize queries to avoid additional database hits which could occur while using such a serializer.
19
20 For example, the following serializer would lead to a database hit each time evaluating the tracks field if it is not prefetched:
21
22 class AlbumSerializer(serializers.ModelSerializer):
23 tracks = serializers.SlugRelatedField(
24 many=True,
25 read_only=True,
26 slug_field='title'
27 )
28
29 class Meta:
30 model = Album
31 fields = ['album_name', 'artist', 'tracks']
32
33 # For each album object, tracks should be fetched from database
34 qs = Album.objects.all()
35 print(AlbumSerializer(qs, many=True).data)
36
37 If `AlbumSerializer` is used to serialize a fairly large queryset with `many=True` then it could be a serious performance problem. Optimizing the queryset passed to `AlbumSerializer` with:
38
39 qs = Album.objects.prefetch_related('tracks')
40 # No additional database hits required
41 print(AlbumSerializer(qs, many=True).data)
42
43 would solve the issue.
44
45 ## Inspecting relationships.
46
47 When using the `ModelSerializer` class, serializer fields and relationships will be automatically generated for you. Inspecting these automatically generated fields can be a useful tool for determining how to customize the relationship style.
48
49 To do so, open the Django shell, using `python manage.py shell`, then import the serializer class, instantiate it, and print the object representation…
50
51 >>> from myapp.serializers import AccountSerializer
52 >>> serializer = AccountSerializer()
53 >>> print(repr(serializer))
54 AccountSerializer():
55 id = IntegerField(label='ID', read_only=True)
56 name = CharField(allow_blank=True, max_length=100, required=False)
57 owner = PrimaryKeyRelatedField(queryset=User.objects.all())
58
59 ## API Reference
60
61 In order to explain the various types of relational fields, we'll use a couple of simple models for our examples. Our models will be for music albums, and the tracks listed on each album.
62
63 class Album(models.Model):
64 album_name = models.CharField(max_length=100)
65 artist = models.CharField(max_length=100)
66
67 class Track(models.Model):
68 album = models.ForeignKey(Album, related_name='tracks', on_delete=models.CASCADE)
69 order = models.IntegerField()
70 title = models.CharField(max_length=100)
71 duration = models.IntegerField()
72
73 class Meta:
74 unique_together = ['album', 'order']
75 ordering = ['order']
76
77 def __str__(self):
78 return '%d: %s' % (self.order, self.title)
79
80 ### StringRelatedField
81
82 `StringRelatedField` may be used to represent the target of the relationship using its `__str__` method.
83
84 For example, the following serializer:
85
86 class AlbumSerializer(serializers.ModelSerializer):
87 tracks = serializers.StringRelatedField(many=True)
88
89 class Meta:
90 model = Album
91 fields = ['album_name', 'artist', 'tracks']
92
93 Would serialize to the following representation:
94
95 {
96 'album_name': 'Things We Lost In The Fire',
97 'artist': 'Low',
98 'tracks': [
99 '1: Sunflower',
100 '2: Whitetail',
101 '3: Dinosaur Act',
102 ...
103 ]
104 }
105
106 This field is read only.
107
108 **Arguments**:
109
110 * `many` - If applied to a to-many relationship, you should set this argument to `True`.
111
112 ### PrimaryKeyRelatedField
113
114 `PrimaryKeyRelatedField` may be used to represent the target of the relationship using its primary key.
115
116 For example, the following serializer:
117
118 class AlbumSerializer(serializers.ModelSerializer):
119 tracks = serializers.PrimaryKeyRelatedField(many=True, read_only=True)
120
121 class Meta:
122 model = Album
123 fields = ['album_name', 'artist', 'tracks']
124
125 Would serialize to a representation like this:
126
127 {
128 'album_name': 'Undun',
129 'artist': 'The Roots',
130 'tracks': [
131 89,
132 90,
133 91,
134 ...
135 ]
136 }
137
138 By default this field is read-write, although you can change this behavior using the `read_only` flag.
139
140 **Arguments**:
141
142 * `queryset` - The queryset used for model instance lookups when validating the field input. Relationships must either set a queryset explicitly, or set `read_only=True`.
143 * `many` - If applied to a to-many relationship, you should set this argument to `True`.
144 * `allow_null` - If set to `True`, the field will accept values of `None` or the empty string for nullable relationships. Defaults to `False`.
145 * `pk_field` - Set to a field to control serialization/deserialization of the primary key's value. For example, `pk_field=UUIDField(format='hex')` would serialize a UUID primary key into its compact hex representation.
146
147
148 ### HyperlinkedRelatedField
149
150 `HyperlinkedRelatedField` may be used to represent the target of the relationship using a hyperlink.
151
152 For example, the following serializer:
153
154 class AlbumSerializer(serializers.ModelSerializer):
155 tracks = serializers.HyperlinkedRelatedField(
156 many=True,
157 read_only=True,
158 view_name='track-detail'
159 )
160
161 class Meta:
162 model = Album
163 fields = ['album_name', 'artist', 'tracks']
164
165 Would serialize to a representation like this:
166
167 {
168 'album_name': 'Graceland',
169 'artist': 'Paul Simon',
170 'tracks': [
171 'http://www.example.com/api/tracks/45/',
172 'http://www.example.com/api/tracks/46/',
173 'http://www.example.com/api/tracks/47/',
174 ...
175 ]
176 }
177
178 By default this field is read-write, although you can change this behavior using the `read_only` flag.
179
180 !!! note
181 This field is designed for objects that map to a URL that accepts a single URL keyword argument, as set using the `lookup_field` and `lookup_url_kwarg` arguments.
182
183 This is suitable for URLs that contain a single primary key or slug argument as part of the URL.
184
185 If you require more complex hyperlinked representation you'll need to customize the field, as described in the [custom hyperlinked fields](#custom-hyperlinked-fields) section, below.
186
187 **Arguments**:
188
189 * `view_name` - The view name that should be used as the target of the relationship. If you're using [the standard router classes][routers] this will be a string with the format `<modelname>-detail`. **required**.
190 * `queryset` - The queryset used for model instance lookups when validating the field input. Relationships must either set a queryset explicitly, or set `read_only=True`.
191 * `many` - If applied to a to-many relationship, you should set this argument to `True`.
192 * `allow_null` - If set to `True`, the field will accept values of `None` or the empty string for nullable relationships. Defaults to `False`.
193 * `lookup_field` - The field on the target that should be used for the lookup. Should correspond to a URL keyword argument on the referenced view. Default is `'pk'`.
194 * `lookup_url_kwarg` - The name of the keyword argument defined in the URL conf that corresponds to the lookup field. Defaults to using the same value as `lookup_field`.
195 * `format` - If using format suffixes, hyperlinked fields will use the same format suffix for the target unless overridden by using the `format` argument.
196
197 ### SlugRelatedField
198
199 `SlugRelatedField` may be used to represent the target of the relationship using a field on the target.
200
201 For example, the following serializer:
202
203 class AlbumSerializer(serializers.ModelSerializer):
204 tracks = serializers.SlugRelatedField(
205 many=True,
206 read_only=True,
207 slug_field='title'
208 )
209
210 class Meta:
211 model = Album
212 fields = ['album_name', 'artist', 'tracks']
213
214 Would serialize to a representation like this:
215
216 {
217 'album_name': 'Dear John',
218 'artist': 'Loney Dear',
219 'tracks': [
220 'Airport Surroundings',
221 'Everything Turns to You',
222 'I Was Only Going Out',
223 ...
224 ]
225 }
226
227 By default this field is read-write, although you can change this behavior using the `read_only` flag.
228
229 When using `SlugRelatedField` as a read-write field, you will normally want to ensure that the slug field corresponds to a model field with `unique=True`.
230
231 **Arguments**:
232
233 * `slug_field` - The field on the target that should be used to represent it. This should be a field that uniquely identifies any given instance. For example, `username`. **required**
234 * `queryset` - The queryset used for model instance lookups when validating the field input. Relationships must either set a queryset explicitly, or set `read_only=True`.
235 * `many` - If applied to a to-many relationship, you should set this argument to `True`.
236 * `allow_null` - If set to `True`, the field will accept values of `None` or the empty string for nullable relationships. Defaults to `False`.
237
238 ### HyperlinkedIdentityField
239
240 This field can be applied as an identity relationship, such as the `'url'` field on a HyperlinkedModelSerializer. It can also be used for an attribute on the object. For example, the following serializer:
241
242 class AlbumSerializer(serializers.HyperlinkedModelSerializer):
243 track_listing = serializers.HyperlinkedIdentityField(view_name='track-list')
244
245 class Meta:
246 model = Album
247 fields = ['album_name', 'artist', 'track_listing']
248
249 Would serialize to a representation like this:
250
251 {
252 'album_name': 'The Eraser',
253 'artist': 'Thom Yorke',
254 'track_listing': 'http://www.example.com/api/track_list/12/',
255 }
256
257 This field is always read-only.
258
259 **Arguments**:
260
261 * `view_name` - The view name that should be used as the target of the relationship. If you're using [the standard router classes][routers] this will be a string with the format `<model_name>-detail`. **required**.
262 * `lookup_field` - The field on the target that should be used for the lookup. Should correspond to a URL keyword argument on the referenced view. Default is `'pk'`.
263 * `lookup_url_kwarg` - The name of the keyword argument defined in the URL conf that corresponds to the lookup field. Defaults to using the same value as `lookup_field`.
264 * `format` - If using format suffixes, hyperlinked fields will use the same format suffix for the target unless overridden by using the `format` argument.
265
266 ---
267
268 ## Nested relationships
269
270 As opposed to previously discussed _references_ to another entity, the referred entity can instead also be embedded or _nested_
271 in the representation of the object that refers to it.
272 Such nested relationships can be expressed by using serializers as fields.
273
274 If the field is used to represent a to-many relationship, you should add the `many=True` flag to the serializer field.
275
276 ### Example
277
278 For example, the following serializer:
279
280 class TrackSerializer(serializers.ModelSerializer):
281 class Meta:
282 model = Track
283 fields = ['order', 'title', 'duration']
284
285 class AlbumSerializer(serializers.ModelSerializer):
286 tracks = TrackSerializer(many=True, read_only=True)
287
288 class Meta:
289 model = Album
290 fields = ['album_name', 'artist', 'tracks']
291
292 Would serialize to a nested representation like this:
293
294 >>> album = Album.objects.create(album_name="The Gray Album", artist='Danger Mouse')
295 >>> Track.objects.create(album=album, order=1, title='Public Service Announcement', duration=245)
296 <Track: Track object>
297 >>> Track.objects.create(album=album, order=2, title='What More Can I Say', duration=264)
298 <Track: Track object>
299 >>> Track.objects.create(album=album, order=3, title='Encore', duration=159)
300 <Track: Track object>
301 >>> serializer = AlbumSerializer(instance=album)
302 >>> serializer.data
303 {
304 'album_name': 'The Gray Album',
305 'artist': 'Danger Mouse',
306 'tracks': [
307 {'order': 1, 'title': 'Public Service Announcement', 'duration': 245},
308 {'order': 2, 'title': 'What More Can I Say', 'duration': 264},
309 {'order': 3, 'title': 'Encore', 'duration': 159},
310 ...
311 ],
312 }
313
314 ### Writable nested serializers
315
316 By default nested serializers are read-only. If you want to support write-operations to a nested serializer field you'll need to create `create()` and/or `update()` methods in order to explicitly specify how the child relationships should be saved:
317
318 class TrackSerializer(serializers.ModelSerializer):
319 class Meta:
320 model = Track
321 fields = ['order', 'title', 'duration']
322
323 class AlbumSerializer(serializers.ModelSerializer):
324 tracks = TrackSerializer(many=True)
325
326 class Meta:
327 model = Album
328 fields = ['album_name', 'artist', 'tracks']
329
330 def create(self, validated_data):
331 tracks_data = validated_data.pop('tracks')
332 album = Album.objects.create(**validated_data)
333 for track_data in tracks_data:
334 Track.objects.create(album=album, **track_data)
335 return album
336
337 >>> data = {
338 'album_name': 'The Gray Album',
339 'artist': 'Danger Mouse',
340 'tracks': [
341 {'order': 1, 'title': 'Public Service Announcement', 'duration': 245},
342 {'order': 2, 'title': 'What More Can I Say', 'duration': 264},
343 {'order': 3, 'title': 'Encore', 'duration': 159},
344 ],
345 }
346 >>> serializer = AlbumSerializer(data=data)
347 >>> serializer.is_valid()
348 True
349 >>> serializer.save()
350 <Album: Album object>
351
352 ---
353
354 ## Custom relational fields
355
356 In rare cases where none of the existing relational styles fit the representation you need,
357 you can implement a completely custom relational field, that describes exactly how the
358 output representation should be generated from the model instance.
359
360 To implement a custom relational field, you should override `RelatedField`, and implement the `.to_representation(self, value)` method. This method takes the target of the field as the `value` argument, and should return the representation that should be used to serialize the target. The `value` argument will typically be a model instance.
361
362 If you want to implement a read-write relational field, you must also implement the [`.to_internal_value(self, data)` method][to_internal_value].
363
364 To provide a dynamic queryset based on the `context`, you can also override `.get_queryset(self)` instead of specifying `.queryset` on the class or when initializing the field.
365
366 ### Example
367
368 For example, we could define a relational field to serialize a track to a custom string representation, using its ordering, title, and duration:
369
370 import time
371
372 class TrackListingField(serializers.RelatedField):
373 def to_representation(self, value):
374 duration = time.strftime('%M:%S', time.gmtime(value.duration))
375 return 'Track %d: %s (%s)' % (value.order, value.name, duration)
376
377 class AlbumSerializer(serializers.ModelSerializer):
378 tracks = TrackListingField(many=True)
379
380 class Meta:
381 model = Album
382 fields = ['album_name', 'artist', 'tracks']
383
384 This custom field would then serialize to the following representation:
385
386 {
387 'album_name': 'Sometimes I Wish We Were an Eagle',
388 'artist': 'Bill Callahan',
389 'tracks': [
390 'Track 1: Jim Cain (04:39)',
391 'Track 2: Eid Ma Clack Shaw (04:19)',
392 'Track 3: The Wind and the Dove (04:34)',
393 ...
394 ]
395 }
396
397 ---
398
399 ## Custom hyperlinked fields
400
401 In some cases you may need to customize the behavior of a hyperlinked field, in order to represent URLs that require more than a single lookup field.
402
403 You can achieve this by overriding `HyperlinkedRelatedField`. There are two methods that may be overridden:
404
405 **get_url(self, obj, view_name, request, format)**
406
407 The `get_url` method is used to map the object instance to its URL representation.
408
409 May raise a `NoReverseMatch` if the `view_name` and `lookup_field`
410 attributes are not configured to correctly match the URL conf.
411
412 **get_object(self, view_name, view_args, view_kwargs)**
413
414 If you want to support a writable hyperlinked field then you'll also want to override `get_object`, in order to map incoming URLs back to the object they represent. For read-only hyperlinked fields there is no need to override this method.
415
416 The return value of this method should the object that corresponds to the matched URL conf arguments.
417
418 May raise an `ObjectDoesNotExist` exception.
419
420 ### Example
421
422 Say we have a URL for a customer object that takes two keyword arguments, like so:
423
424 /api/<organization_slug>/customers/<customer_pk>/
425
426 This cannot be represented with the default implementation, which accepts only a single lookup field.
427
428 In this case we'd need to override `HyperlinkedRelatedField` to get the behavior we want:
429
430 from rest_framework import serializers
431 from rest_framework.reverse import reverse
432
433 class CustomerHyperlink(serializers.HyperlinkedRelatedField):
434 # We define these as class attributes, so we don't need to pass them as arguments.
435 view_name = 'customer-detail'
436 queryset = Customer.objects.all()
437
438 def get_url(self, obj, view_name, request, format):
439 url_kwargs = {
440 'organization_slug': obj.organization.slug,
441 'customer_pk': obj.pk
442 }
443 return reverse(view_name, kwargs=url_kwargs, request=request, format=format)
444
445 def get_object(self, view_name, view_args, view_kwargs):
446 lookup_kwargs = {
447 'organization__slug': view_kwargs['organization_slug'],
448 'pk': view_kwargs['customer_pk']
449 }
450 return self.get_queryset().get(**lookup_kwargs)
451
452 Note that if you wanted to use this style together with the generic views then you'd also need to override `.get_object` on the view in order to get the correct lookup behavior.
453
454 Generally we recommend a flat style for API representations where possible, but the nested URL style can also be reasonable when used in moderation.
455
456 ---
457
458 ## Further notes
459
460 ### The `queryset` argument
461
462 The `queryset` argument is only ever required for *writable* relationship field, in which case it is used for performing the model instance lookup, that maps from the primitive user input, into a model instance.
463
464 In version 2.x a serializer class could *sometimes* automatically determine the `queryset` argument *if* a `ModelSerializer` class was being used.
465
466 This behavior is now replaced with *always* using an explicit `queryset` argument for writable relational fields.
467
468 Doing so reduces the amount of hidden 'magic' that `ModelSerializer` provides, makes the behavior of the field more clear, and ensures that it is trivial to move between using the `ModelSerializer` shortcut, or using fully explicit `Serializer` classes.
469
470 ### Customizing the HTML display
471
472 The built-in `__str__` method of the model will be used to generate string representations of the objects used to populate the `choices` property. These choices are used to populate select HTML inputs in the browsable API.
473
474 To provide customized representations for such inputs, override `display_value()` of a `RelatedField` subclass. This method will receive a model object, and should return a string suitable for representing it. For example:
475
476 class TrackPrimaryKeyRelatedField(serializers.PrimaryKeyRelatedField):
477 def display_value(self, instance):
478 return 'Track: %s' % (instance.title)
479
480 ### Select field cutoffs
481
482 When rendered in the browsable API relational fields will default to only displaying a maximum of 1000 selectable items. If more items are present then a disabled option with "More than 1000 items…" will be displayed.
483
484 This behavior is intended to prevent a template from being unable to render in an acceptable timespan due to a very large number of relationships being displayed.
485
486 There are two keyword arguments you can use to control this behavior:
487
488 * `html_cutoff` - If set this will be the maximum number of choices that will be displayed by a HTML select drop down. Set to `None` to disable any limiting. Defaults to `1000`.
489 * `html_cutoff_text` - If set this will display a textual indicator if the maximum number of items have been cutoff in an HTML select drop down. Defaults to `"More than {count} items…"`
490
491 You can also control these globally using the settings `HTML_SELECT_CUTOFF` and `HTML_SELECT_CUTOFF_TEXT`.
492
493 In cases where the cutoff is being enforced you may want to instead use a plain input field in the HTML form. You can do so using the `style` keyword argument. For example:
494
495 assigned_to = serializers.SlugRelatedField(
496 queryset=User.objects.all(),
497 slug_field='username',
498 style={'base_template': 'input.html'}
499 )
500
501 ### Reverse relations
502
503 Note that reverse relationships are not automatically included by the `ModelSerializer` and `HyperlinkedModelSerializer` classes. To include a reverse relationship, you must explicitly add it to the fields list. For example:
504
505 class AlbumSerializer(serializers.ModelSerializer):
506 class Meta:
507 fields = ['tracks', ...]
508
509 You'll normally want to ensure that you've set an appropriate `related_name` argument on the relationship, that you can use as the field name. For example:
510
511 class Track(models.Model):
512 album = models.ForeignKey(Album, related_name='tracks', on_delete=models.CASCADE)
513 ...
514
515 If you have not set a related name for the reverse relationship, you'll need to use the automatically generated related name in the `fields` argument. For example:
516
517 class AlbumSerializer(serializers.ModelSerializer):
518 class Meta:
519 fields = ['track_set', ...]
520
521 See the Django documentation on [reverse relationships][reverse-relationships] for more details.
522
523 ### Generic relationships
524
525 If you want to serialize a generic foreign key, you need to define a custom field, to determine explicitly how you want to serialize the targets of the relationship.
526
527 For example, given the following model for a tag, which has a generic relationship with other arbitrary models:
528
529 class TaggedItem(models.Model):
530 """
531 Tags arbitrary model instances using a generic relation.
532
533 See: https://docs.djangoproject.com/en/stable/ref/contrib/contenttypes/
534 """
535 tag_name = models.SlugField()
536 content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
537 object_id = models.PositiveIntegerField()
538 tagged_object = GenericForeignKey('content_type', 'object_id')
539
540 def __str__(self):
541 return self.tag_name
542
543 And the following two models, which may have associated tags:
544
545 class Bookmark(models.Model):
546 """
547 A bookmark consists of a URL, and 0 or more descriptive tags.
548 """
549 url = models.URLField()
550 tags = GenericRelation(TaggedItem)
551
552
553 class Note(models.Model):
554 """
555 A note consists of some text, and 0 or more descriptive tags.
556 """
557 text = models.CharField(max_length=1000)
558 tags = GenericRelation(TaggedItem)
559
560 We could define a custom field that could be used to serialize tagged instances, using the type of each instance to determine how it should be serialized:
561
562 class TaggedObjectRelatedField(serializers.RelatedField):
563 """
564 A custom field to use for the `tagged_object` generic relationship.
565 """
566
567 def to_representation(self, value):
568 """
569 Serialize tagged objects to a simple textual representation.
570 """
571 if isinstance(value, Bookmark):
572 return 'Bookmark: ' + value.url
573 elif isinstance(value, Note):
574 return 'Note: ' + value.text
575 raise Exception('Unexpected type of tagged object')
576
577 If you need the target of the relationship to have a nested representation, you can use the required serializers inside the `.to_representation()` method:
578
579 def to_representation(self, value):
580 """
581 Serialize bookmark instances using a bookmark serializer,
582 and note instances using a note serializer.
583 """
584 if isinstance(value, Bookmark):
585 serializer = BookmarkSerializer(value)
586 elif isinstance(value, Note):
587 serializer = NoteSerializer(value)
588 else:
589 raise Exception('Unexpected type of tagged object')
590
591 return serializer.data
592
593 Note that reverse generic keys, expressed using the `GenericRelation` field, can be serialized using the regular relational field types, since the type of the target in the relationship is always known.
594
595 For more information see [the Django documentation on generic relations][generic-relations].
596
597 ### ManyToManyFields with a Through Model
598
599 By default, relational fields that target a ``ManyToManyField`` with a
600 ``through`` model specified are set to read-only.
601
602 If you explicitly specify a relational field pointing to a
603 ``ManyToManyField`` with a through model, be sure to set ``read_only``
604 to ``True``.
605
606 If you wish to represent [extra fields on a through model][django-intermediary-manytomany] then you may serialize the through model as [a nested object][dealing-with-nested-objects].
607
608 ---
609
610 ## Third Party Packages
611
612 The following third party packages are also available.
613
614 ### DRF Nested Routers
615
616 The [drf-nested-routers package][drf-nested-routers] provides routers and relationship fields for working with nested resources.
617
618 ### Rest Framework Generic Relations
619
620 The [rest-framework-generic-relations][drf-nested-relations] library provides read/write serialization for generic foreign keys.
621
622 The [rest-framework-gm2m-relations][drf-gm2m-relations] library provides read/write serialization for [django-gm2m][django-gm2m-field].
623
624 [cite]: http://users.ece.utexas.edu/~adnan/pike.html
625 [reverse-relationships]: https://docs.djangoproject.com/en/stable/topics/db/queries/#following-relationships-backward
626 [routers]: https://www.django-rest-framework.org/api-guide/routers#defaultrouter
627 [generic-relations]: https://docs.djangoproject.com/en/stable/ref/contrib/contenttypes/#id1
628 [drf-nested-routers]: https://github.com/alanjds/drf-nested-routers
629 [drf-nested-relations]: https://github.com/Ian-Foote/rest-framework-generic-relations
630 [drf-gm2m-relations]: https://github.com/mojtabaakbari221b/rest-framework-gm2m-relations
631 [django-gm2m-field]: https://github.com/tkhyn/django-gm2m
632 [django-intermediary-manytomany]: https://docs.djangoproject.com/en/stable/topics/db/models/#intermediary-manytomany
633 [dealing-with-nested-objects]: https://www.django-rest-framework.org/api-guide/serializers/#dealing-with-nested-objects
634 [to_internal_value]: https://www.django-rest-framework.org/api-guide/serializers/#to_internal_valueself-data