aboutsummaryrefslogtreecommitdiffstats
path: root/api-guide/relations.html
blob: 64e5d98904a7f4af8cdd849d110e070568882325 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
<!DOCTYPE html>
<html lang="en">
<head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <meta charset="utf-8">
    <title>Serializer relations - Django REST framework</title>
    <link href="http://www.django-rest-framework.org/img/favicon.ico" rel="icon" type="image/x-icon">
    <link rel="canonical" href="http://www.django-rest-framework.org/api-guide/relations"/>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="Django, API, REST, Serializer relations, API Reference, Nested relationships, Custom relational fields, Further notes, Third Party Packages">
    <meta name="author" content="Tom Christie">

    <!-- Le styles -->
    <link href="http://www.django-rest-framework.org/css/prettify.css" rel="stylesheet">
    <link href="http://www.django-rest-framework.org/css/bootstrap.css" rel="stylesheet">
    <link href="http://www.django-rest-framework.org/css/bootstrap-responsive.css" rel="stylesheet">
    <link href="http://www.django-rest-framework.org/css/default.css" rel="stylesheet">

    <!-- Le HTML5 shim, for IE6-8 support of HTML5 elements -->
    <!--[if lt IE 9]>
      <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
    <![endif]-->

    <script type="text/javascript">

  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-18852272-2']);
  _gaq.push(['_trackPageview']);

  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  })();

    </script>
    <style>
span.fusion-wrap a {
  display: block;
  margin-top: 10px;
  color: black;
}

a.fusion-poweredby {
  display: block;
  margin-top: 10px;
}
@media (max-width: 767px) {
  div.promo {display: none;}
}
</style>
  </head>
  <body onload="prettyPrint()" class="relations-page">

  <div class="wrapper">

    <div class="navbar navbar-inverse navbar-fixed-top">
      <div class="navbar-inner">
        <div class="container-fluid">
            <a class="repo-link btn btn-primary btn-small" href="https://github.com/tomchristie/django-rest-framework/tree/master">GitHub</a>
            <a class="repo-link btn btn-inverse btn-small " href="../api-guide/authentication">Next <i class="icon-arrow-right icon-white"></i></a>
            <a class="repo-link btn btn-inverse btn-small " href="../api-guide/fields"><i class="icon-arrow-left icon-white"></i> Previous</a>
            <a class="repo-link btn btn-inverse btn-small" href="#searchModal" data-toggle="modal"><i class="icon-search icon-white"></i> Search</a>
          <a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
          </a>
          <a class="brand" href="http://www.django-rest-framework.org">Django REST framework</a>
          <div class="nav-collapse collapse">
            <ul class="nav">
              <li><a href="http://www.django-rest-framework.org">Home</a></li>
              <li class="dropdown">
                <a href="#" class="dropdown-toggle" data-toggle="dropdown">Tutorial <b class="caret"></b></a>
                <ul class="dropdown-menu">
                  <li><a href="http://www.django-rest-framework.org/tutorial/quickstart">Quickstart</a></li>
                  <li><a href="http://www.django-rest-framework.org/tutorial/1-serialization">1 - Serialization</a></li>
                  <li><a href="http://www.django-rest-framework.org/tutorial/2-requests-and-responses">2 - Requests and responses</a></li>
                  <li><a href="http://www.django-rest-framework.org/tutorial/3-class-based-views">3 - Class based views</a></li>
                  <li><a href="http://www.django-rest-framework.org/tutorial/4-authentication-and-permissions">4 - Authentication and permissions</a></li>
                  <li><a href="http://www.django-rest-framework.org/tutorial/5-relationships-and-hyperlinked-apis">5 - Relationships and hyperlinked APIs</a></li>
                  <li><a href="http://www.django-rest-framework.org/tutorial/6-viewsets-and-routers">6 - Viewsets and routers</a></li>
                </ul>
              </li>
              <li class="dropdown">
                <a href="#" class="dropdown-toggle" data-toggle="dropdown">API Guide <b class="caret"></b></a>
                <ul class="dropdown-menu">
                  <li><a href="http://www.django-rest-framework.org/api-guide/requests">Requests</a></li>
                  <li><a href="http://www.django-rest-framework.org/api-guide/responses">Responses</a></li>
                  <li><a href="http://www.django-rest-framework.org/api-guide/views">Views</a></li>
                  <li><a href="http://www.django-rest-framework.org/api-guide/generic-views">Generic views</a></li>
                  <li><a href="http://www.django-rest-framework.org/api-guide/viewsets">Viewsets</a></li>
                  <li><a href="http://www.django-rest-framework.org/api-guide/routers">Routers</a></li>
                  <li><a href="http://www.django-rest-framework.org/api-guide/parsers">Parsers</a></li>
                  <li><a href="http://www.django-rest-framework.org/api-guide/renderers">Renderers</a></li>
                  <li><a href="http://www.django-rest-framework.org/api-guide/serializers">Serializers</a></li>
                  <li><a href="http://www.django-rest-framework.org/api-guide/fields">Serializer fields</a></li>
                  <li><a href="http://www.django-rest-framework.org/api-guide/relations">Serializer relations</a></li>
                  <li><a href="http://www.django-rest-framework.org/api-guide/authentication">Authentication</a></li>
                  <li><a href="http://www.django-rest-framework.org/api-guide/permissions">Permissions</a></li>
                  <li><a href="http://www.django-rest-framework.org/api-guide/throttling">Throttling</a></li>
                  <li><a href="http://www.django-rest-framework.org/api-guide/filtering">Filtering</a></li>
                  <li><a href="http://www.django-rest-framework.org/api-guide/pagination">Pagination</a></li>
                  <li><a href="http://www.django-rest-framework.org/api-guide/content-negotiation">Content negotiation</a></li>
                  <li><a href="http://www.django-rest-framework.org/api-guide/format-suffixes">Format suffixes</a></li>
                  <li><a href="http://www.django-rest-framework.org/api-guide/reverse">Returning URLs</a></li>
                  <li><a href="http://www.django-rest-framework.org/api-guide/exceptions">Exceptions</a></li>
                  <li><a href="http://www.django-rest-framework.org/api-guide/status-codes">Status codes</a></li>
                  <li><a href="http://www.django-rest-framework.org/api-guide/testing">Testing</a></li>
                  <li><a href="http://www.django-rest-framework.org/api-guide/settings">Settings</a></li>
                </ul>
              </li>
              <li class="dropdown">
                <a href="#" class="dropdown-toggle" data-toggle="dropdown">Topics <b class="caret"></b></a>
                <ul class="dropdown-menu">
                  <li><a href="http://www.django-rest-framework.org/topics/documenting-your-api">Documenting your API</a></li>
                  <li><a href="http://www.django-rest-framework.org/topics/ajax-csrf-cors">AJAX, CSRF & CORS</a></li>
                  <li><a href="http://www.django-rest-framework.org/topics/browser-enhancements">Browser enhancements</a></li>
                  <li><a href="http://www.django-rest-framework.org/topics/browsable-api">The Browsable API</a></li>
                  <li><a href="http://www.django-rest-framework.org/topics/rest-hypermedia-hateoas">REST, Hypermedia & HATEOAS</a></li>
                  <li><a href="http://www.django-rest-framework.org/topics/third-party-resources">Third Party Resources</a></li>
                  <li><a href="http://www.django-rest-framework.org/topics/contributing">Contributing to REST framework</a></li>
                  <li><a href="http://www.django-rest-framework.org/topics/rest-framework-2-announcement">2.0 Announcement</a></li>
                  <li><a href="http://www.django-rest-framework.org/topics/2.2-announcement">2.2 Announcement</a></li>
                  <li><a href="http://www.django-rest-framework.org/topics/2.3-announcement">2.3 Announcement</a></li>
                  <li><a href="http://www.django-rest-framework.org/topics/2.4-announcement">2.4 Announcement</a></li>
                  <li><a href="http://www.django-rest-framework.org/topics/kickstarter-announcement">Kickstarter Announcement</a></li>
                  <li><a href="http://www.django-rest-framework.org/topics/release-notes">Release Notes</a></li>
                  <li><a href="http://www.django-rest-framework.org/topics/credits">Credits</a></li>
                </ul>
              </li>
            </ul>
            <ul class="nav pull-right">
              <!-- TODO
              <li class="dropdown">
                <a href="#" class="dropdown-toggle" data-toggle="dropdown">Version: 2.0.0 <b class="caret"></b></a>
                <ul class="dropdown-menu">
                  <li><a href="#">Trunk</a></li>
                  <li><a href="#">2.0.0</a></li>
                </ul>
              </li>
            -->
            </ul>
          </div><!--/.nav-collapse -->
        </div>
      </div>
    </div>

    <div class="body-content">
      <div class="container-fluid">

<!-- Search Modal -->
<div id="searchModal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  <div class="modal-header">
    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
    <h3 id="myModalLabel">Documentation search</h3>
  </div>
  <div class="modal-body">
    <!-- Custom google search -->
    <script>
      (function() {
        var cx = '015016005043623903336:rxraeohqk6w';
        var gcse = document.createElement('script');
        gcse.type = 'text/javascript';
        gcse.async = true;
        gcse.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') +
            '//www.google.com/cse/cse.js?cx=' + cx;
        var s = document.getElementsByTagName('script')[0];
        s.parentNode.insertBefore(gcse, s);
      })();
    </script>
    <gcse:search></gcse:search>
  </div>
  <div class="modal-footer">
    <button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
  </div>
</div>

        <div class="row-fluid">

          <div class="span3">
            <!-- TODO
            <p style="margin-top: -12px">
              <a class="btn btn-mini btn-primary" style="width: 60px">&laquo; previous</a>
              <a class="btn btn-mini btn-primary" style="float: right; margin-right: 8px; width: 60px;">next &raquo;</a>
            </p>
          -->
            <div id="table-of-contents">
              <ul class="nav nav-list side-nav well sidebar-nav-fixed">
                <li class="main"><a href="#serializer-relations">Serializer relations</a></li>
<li class="main"><a href="#api-reference">API Reference</a></li>
<li><a href="#relatedfield">RelatedField</a></li>
<li><a href="#primarykeyrelatedfield">PrimaryKeyRelatedField</a></li>
<li><a href="#hyperlinkedrelatedfield">HyperlinkedRelatedField</a></li>
<li><a href="#slugrelatedfield">SlugRelatedField</a></li>
<li><a href="#hyperlinkedidentityfield">HyperlinkedIdentityField</a></li>
<li class="main"><a href="#nested-relationships">Nested relationships</a></li>
<li><a href="#example">Example</a></li>
<li class="main"><a href="#custom-relational-fields">Custom relational fields</a></li>
<li><a href="#example">Example</a></li>
<li class="main"><a href="#further-notes">Further notes</a></li>
<li><a href="#reverse-relations">Reverse relations</a></li>
<li><a href="#generic-relationships">Generic relationships</a></li>
<li><a href="#manytomanyfields-with-a-through-model">ManyToManyFields with a Through Model</a></li>
<li><a href="#advanced-hyperlinked-fields">Advanced Hyperlinked fields</a></li>
<li><a href="#deprecated-apis">Deprecated APIs</a></li>
<li class="main"><a href="#third-party-packages">Third Party Packages</a></li>
<li><a href="#drf-nested-routers">DRF Nested Routers</a></li>

              <div class="promo">
              
              </div>
</ul>

            </div>
          </div>

          <div id="main-content" class="span9">
            <p><a class="github" href="https://github.com/tomchristie/django-rest-framework/tree/master/rest_framework/relations.py"><span class="label label-info">relations.py</span></a></p>
<h1 id="serializer-relations">Serializer relations</h1>
<blockquote>
<p>Bad programmers worry about the code.
Good programmers worry about data structures and their relationships.</p>
<p>&mdash; <a href="http://lwn.net/Articles/193245/">Linus Torvalds</a></p>
</blockquote>
<p>Relational fields are used to represent model relationships.  They can be applied to <code>ForeignKey</code>, <code>ManyToManyField</code> and <code>OneToOneField</code> relationships, as well as to reverse relationships, and custom relationships such as <code>GenericForeignKey</code>.</p>
<hr />
<p><strong>Note:</strong> The relational fields are declared in <code>relations.py</code>, but by convention you should import them from the <code>serializers</code> module, using <code>from rest_framework import serializers</code> and refer to fields as <code>serializers.&lt;FieldName&gt;</code>.</p>
<hr />
<h1 id="api-reference">API Reference</h1>
<p>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.</p>
<pre class="prettyprint lang-py"><code>class Album(models.Model):
    album_name = models.CharField(max_length=100)
    artist = models.CharField(max_length=100)

class Track(models.Model):
    album = models.ForeignKey(Album, related_name='tracks')
    order = models.IntegerField()
    title = models.CharField(max_length=100)
    duration = models.IntegerField()

    class Meta:
        unique_together = ('album', 'order')
        order_by = 'order'

    def __unicode__(self):
        return '%d: %s' % (self.order, self.title)
</code></pre>
<h2 id="relatedfield">RelatedField</h2>
<p><code>RelatedField</code> may be used to represent the target of the relationship using its <code>__unicode__</code> method.</p>
<p>For example, the following serializer.</p>
<pre class="prettyprint lang-py"><code>class AlbumSerializer(serializers.ModelSerializer):
    tracks = serializers.RelatedField(many=True)

    class Meta:
        model = Album
        fields = ('album_name', 'artist', 'tracks')
</code></pre>
<p>Would serialize to the following representation.</p>
<pre class="prettyprint lang-py"><code>{
    'album_name': 'Things We Lost In The Fire',
    'artist': 'Low',
    'tracks': [
        '1: Sunflower',
        '2: Whitetail',
        '3: Dinosaur Act',
        ...
    ]
}
</code></pre>
<p>This field is read only.</p>
<p><strong>Arguments</strong>:</p>
<ul>
<li><code>many</code> - If applied to a to-many relationship, you should set this argument to <code>True</code>.</li>
</ul>
<h2 id="primarykeyrelatedfield">PrimaryKeyRelatedField</h2>
<p><code>PrimaryKeyRelatedField</code> may be used to represent the target of the relationship using its primary key.</p>
<p>For example, the following serializer:</p>
<pre class="prettyprint lang-py"><code>class AlbumSerializer(serializers.ModelSerializer):
    tracks = serializers.PrimaryKeyRelatedField(many=True, read_only=True)

    class Meta:
        model = Album
        fields = ('album_name', 'artist', 'tracks')
</code></pre>
<p>Would serialize to a representation like this:</p>
<pre class="prettyprint lang-py"><code>{
    'album_name': 'The Roots',
    'artist': 'Undun',
    'tracks': [
        89,
        90,
        91,
        ...
    ]
}
</code></pre>
<p>By default this field is read-write, although you can change this behavior using the <code>read_only</code> flag.</p>
<p><strong>Arguments</strong>:</p>
<ul>
<li><code>many</code> - If applied to a to-many relationship, you should set this argument to <code>True</code>.</li>
<li><code>required</code> - If set to <code>False</code>, the field will accept values of <code>None</code> or the empty-string for nullable relationships.</li>
<li><code>queryset</code> - By default <code>ModelSerializer</code> classes will use the default queryset for the relationship.  <code>Serializer</code> classes must either set a queryset explicitly, or set <code>read_only=True</code>.</li>
</ul>
<h2 id="hyperlinkedrelatedfield">HyperlinkedRelatedField</h2>
<p><code>HyperlinkedRelatedField</code> may be used to represent the target of the relationship using a hyperlink.</p>
<p>For example, the following serializer:</p>
<pre class="prettyprint lang-py"><code>class AlbumSerializer(serializers.ModelSerializer):
    tracks = serializers.HyperlinkedRelatedField(many=True, read_only=True,
                                                 view_name='track-detail')

    class Meta:
        model = Album
        fields = ('album_name', 'artist', 'tracks')
</code></pre>
<p>Would serialize to a representation like this:</p>
<pre class="prettyprint lang-py"><code>{
    'album_name': 'Graceland',
    'artist': 'Paul Simon',
    'tracks': [
        'http://www.example.com/api/tracks/45/',
        'http://www.example.com/api/tracks/46/',
        'http://www.example.com/api/tracks/47/',
        ...
    ]
}
</code></pre>
<p>By default this field is read-write, although you can change this behavior using the <code>read_only</code> flag.</p>
<p><strong>Arguments</strong>:</p>
<ul>
<li><code>view_name</code> - The view name that should be used as the target of the relationship.  If you're using <a href="http://www.django-rest-framework.org/api-guide/routers#defaultrouter">the standard router classes</a> this wil be a string with the format <code>&lt;modelname&gt;-detail</code>. <strong>required</strong>.</li>
<li><code>many</code> - If applied to a to-many relationship, you should set this argument to <code>True</code>.</li>
<li><code>required</code> - If set to <code>False</code>, the field will accept values of <code>None</code> or the empty-string for nullable relationships.</li>
<li><code>queryset</code> - By default <code>ModelSerializer</code> classes will use the default queryset for the relationship.  <code>Serializer</code> classes must either set a queryset explicitly, or set <code>read_only=True</code>.</li>
<li><code>lookup_field</code> - 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 <code>'pk'</code>.</li>
<li><code>format</code> - If using format suffixes, hyperlinked fields will use the same format suffix for the target unless overridden by using the <code>format</code> argument.</li>
</ul>
<h2 id="slugrelatedfield">SlugRelatedField</h2>
<p><code>SlugRelatedField</code> may be used to represent the target of the relationship using a field on the target.</p>
<p>For example, the following serializer:</p>
<pre class="prettyprint lang-py"><code>class AlbumSerializer(serializers.ModelSerializer):
    tracks = serializers.SlugRelatedField(many=True, read_only=True,
                                          slug_field='title')

    class Meta:
        model = Album
        fields = ('album_name', 'artist', 'tracks')
</code></pre>
<p>Would serialize to a representation like this:</p>
<pre class="prettyprint lang-py"><code>{
    'album_name': 'Dear John',
    'artist': 'Loney Dear',
    'tracks': [
        'Airport Surroundings',
        'Everything Turns to You',
        'I Was Only Going Out',
        ...
    ]
}
</code></pre>
<p>By default this field is read-write, although you can change this behavior using the <code>read_only</code> flag.</p>
<p>When using <code>SlugRelatedField</code> as a read-write field, you will normally want to ensure that the slug field corresponds to a model field with <code>unique=True</code>.</p>
<p><strong>Arguments</strong>:</p>
<ul>
<li><code>slug_field</code> - 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, <code>username</code>.  <strong>required</strong></li>
<li><code>many</code> - If applied to a to-many relationship, you should set this argument to <code>True</code>.</li>
<li><code>required</code> - If set to <code>False</code>, the field will accept values of <code>None</code> or the empty-string for nullable relationships.</li>
<li><code>queryset</code> - By default <code>ModelSerializer</code> classes will use the default queryset for the relationship.  <code>Serializer</code> classes must either set a queryset explicitly, or set <code>read_only=True</code>.</li>
</ul>
<h2 id="hyperlinkedidentityfield">HyperlinkedIdentityField</h2>
<p>This field can be applied as an identity relationship, such as the <code>'url'</code> field on  a HyperlinkedModelSerializer.  It can also be used for an attribute on the object.  For example, the following serializer:</p>
<pre class="prettyprint lang-py"><code>class AlbumSerializer(serializers.HyperlinkedModelSerializer):
    track_listing = serializers.HyperlinkedIdentityField(view_name='track-list')

    class Meta:
        model = Album
        fields = ('album_name', 'artist', 'track_listing')
</code></pre>
<p>Would serialize to a representation like this:</p>
<pre class="prettyprint lang-py"><code>{
    'album_name': 'The Eraser',
    'artist': 'Thom Yorke',
    'track_listing': 'http://www.example.com/api/track_list/12/',
}
</code></pre>
<p>This field is always read-only.</p>
<p><strong>Arguments</strong>:</p>
<ul>
<li><code>view_name</code> - The view name that should be used as the target of the relationship.  If you're using <a href="http://www.django-rest-framework.org/api-guide/routers#defaultrouter">the standard router classes</a> this wil be a string with the format <code>&lt;model_name&gt;-detail</code>.  <strong>required</strong>.</li>
<li><code>lookup_field</code> - 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 <code>'pk'</code>.</li>
<li><code>format</code> - If using format suffixes, hyperlinked fields will use the same format suffix for the target unless overridden by using the <code>format</code> argument.</li>
</ul>
<hr />
<h1 id="nested-relationships">Nested relationships</h1>
<p>Nested relationships can be expressed by using serializers as fields.</p>
<p>If the field is used to represent a to-many relationship, you should add the <code>many=True</code> flag to the serializer field.</p>
<h2 id="example">Example</h2>
<p>For example, the following serializer:</p>
<pre class="prettyprint lang-py"><code>class TrackSerializer(serializers.ModelSerializer):
    class Meta:
        model = Track
        fields = ('order', 'title')

class AlbumSerializer(serializers.ModelSerializer):
    tracks = TrackSerializer(many=True)

    class Meta:
        model = Album
        fields = ('album_name', 'artist', 'tracks')
</code></pre>
<p>Would serialize to a nested representation like this:</p>
<pre class="prettyprint lang-py"><code>{
    'album_name': 'The Grey Album',
    'artist': 'Danger Mouse',
    'tracks': [
        {'order': 1, 'title': 'Public Service Announcement'},
        {'order': 2, 'title': 'What More Can I Say'},
        {'order': 3, 'title': 'Encore'},
        ...
    ],
}
</code></pre>
<h1 id="custom-relational-fields">Custom relational fields</h1>
<p>To implement a custom relational field, you should override <code>RelatedField</code>, and implement the <code>.to_native(self, value)</code> method.  This method takes the target of the field as the <code>value</code> argument, and should return the representation that should be used to serialize the target.</p>
<p>If you want to implement a read-write relational field, you must also implement the <code>.from_native(self, data)</code> method, and add <code>read_only = False</code> to the class definition.</p>
<h2 id="example_1">Example</h2>
<p>For, example, we could define a relational field, to serialize a track to a custom string representation, using its ordering, title, and duration.</p>
<pre class="prettyprint lang-py"><code>import time

class TrackListingField(serializers.RelatedField):
    def to_native(self, value):
        duration = time.strftime('%M:%S', time.gmtime(value.duration))
        return 'Track %d: %s (%s)' % (value.order, value.name, duration)

class AlbumSerializer(serializers.ModelSerializer):
    tracks = TrackListingField(many=True)

    class Meta:
        model = Album
        fields = ('album_name', 'artist', 'tracks')
</code></pre>
<p>This custom field would then serialize to the following representation.</p>
<pre class="prettyprint lang-py"><code>{
    'album_name': 'Sometimes I Wish We Were an Eagle',
    'artist': 'Bill Callahan',
    'tracks': [
        'Track 1: Jim Cain (04:39)',
        'Track 2: Eid Ma Clack Shaw (04:19)',
        'Track 3: The Wind and the Dove (04:34)',
        ...
    ]
}
</code></pre>
<hr />
<h1 id="further-notes">Further notes</h1>
<h2 id="reverse-relations">Reverse relations</h2>
<p>Note that reverse relationships are not automatically included by the <code>ModelSerializer</code> and <code>HyperlinkedModelSerializer</code> classes.  To include a reverse relationship, you must explicitly add it to the fields list.  For example:</p>
<pre class="prettyprint lang-py"><code>class AlbumSerializer(serializers.ModelSerializer):
    class Meta:
        fields = ('tracks', ...)
</code></pre>
<p>You'll normally want to ensure that you've set an appropriate <code>related_name</code> argument on the relationship, that you can use as the field name.  For example:</p>
<pre class="prettyprint lang-py"><code>class Track(models.Model):
    album = models.ForeignKey(Album, related_name='tracks')
    ...
</code></pre>
<p>If you have not set a related name for the reverse relationship, you'll need to use the automatically generated related name in the <code>fields</code> argument.  For example:</p>
<pre class="prettyprint lang-py"><code>class AlbumSerializer(serializers.ModelSerializer):
    class Meta:
        fields = ('track_set', ...)
</code></pre>
<p>See the Django documentation on <a href="https://docs.djangoproject.com/en/dev/topics/db/queries/#following-relationships-backward">reverse relationships</a> for more details.</p>
<h2 id="generic-relationships">Generic relationships</h2>
<p>If you want to serialize a generic foreign key, you need to define a custom field, to determine explicitly how you want serialize the targets of the relationship.</p>
<p>For example, given the following model for a tag, which has a generic relationship with other arbitrary models:</p>
<pre class="prettyprint lang-py"><code>class TaggedItem(models.Model):
    """
    Tags arbitrary model instances using a generic relation.

    See: https://docs.djangoproject.com/en/dev/ref/contrib/contenttypes/
    """
    tag_name = models.SlugField()
    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField()
    tagged_object = GenericForeignKey('content_type', 'object_id')

    def __unicode__(self):
        return self.tag
</code></pre>
<p>And the following two models, which may be have associated tags:</p>
<pre class="prettyprint lang-py"><code>class Bookmark(models.Model):
    """
    A bookmark consists of a URL, and 0 or more descriptive tags.
    """
    url = models.URLField()
    tags = GenericRelation(TaggedItem)


class Note(models.Model):
    """
    A note consists of some text, and 0 or more descriptive tags.
    """
    text = models.CharField(max_length=1000)
    tags = GenericRelation(TaggedItem)
</code></pre>
<p>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.</p>
<pre class="prettyprint lang-py"><code>class TaggedObjectRelatedField(serializers.RelatedField):
    """
    A custom field to use for the `tagged_object` generic relationship.
    """

    def to_native(self, value):
        """
        Serialize tagged objects to a simple textual representation.
        """                            
        if isinstance(value, Bookmark):
            return 'Bookmark: ' + value.url
        elif isinstance(value, Note):
            return 'Note: ' + value.text
        raise Exception('Unexpected type of tagged object')
</code></pre>
<p>If you need the target of the relationship to have a nested representation, you can  use the required serializers inside the <code>.to_native()</code> method:</p>
<pre class="prettyprint lang-py"><code>    def to_native(self, value):
        """
        Serialize bookmark instances using a bookmark serializer,
        and note instances using a note serializer.
        """                            
        if isinstance(value, Bookmark):
            serializer = BookmarkSerializer(value)
        elif isinstance(value, Note):
            serializer = NoteSerializer(value)
        else:
            raise Exception('Unexpected type of tagged object')

        return serializer.data
</code></pre>
<p>Note that reverse generic keys, expressed using the <code>GenericRelation</code> field, can be serialized using the regular relational field types, since the type of the target in the relationship is always known.</p>
<p>For more information see <a href="https://docs.djangoproject.com/en/dev/ref/contrib/contenttypes/#id1">the Django documentation on generic relations</a>.</p>
<h2 id="manytomanyfields-with-a-through-model">ManyToManyFields with a Through Model</h2>
<p>By default, relational fields that target a <code>ManyToManyField</code> with a
<code>through</code> model specified are set to read-only.</p>
<p>If you explicitly specify a relational field pointing to a
<code>ManyToManyField</code> with a through model, be sure to set <code>read_only</code>
to <code>True</code>.</p>
<h2 id="advanced-hyperlinked-fields">Advanced Hyperlinked fields</h2>
<p>If you have very specific requirements for the style of your hyperlinked relationships you can override <code>HyperlinkedRelatedField</code>. </p>
<p>There are two methods you'll need to override.</p>
<h4 id="get_urlself-obj-view_name-request-format">get_url(self, obj, view_name, request, format)</h4>
<p>This method should return the URL that corresponds to the given object.</p>
<p>May raise a <code>NoReverseMatch</code> if the <code>view_name</code> and <code>lookup_field</code>
attributes are not configured to correctly match the URL conf.</p>
<h4 id="get_objectself-queryset-view_name-view_args-view_kwargs">get_object(self, queryset, view_name, view_args, view_kwargs)</h4>
<p>This method should the object that corresponds to the matched URL conf arguments.</p>
<p>May raise an <code>ObjectDoesNotExist</code> exception.</p>
<h3 id="example_2">Example</h3>
<p>For example, if all your object URLs used both a account and a slug in the the URL to reference the object, you might create a custom field like this: </p>
<pre class="prettyprint lang-py"><code>class CustomHyperlinkedField(serializers.HyperlinkedRelatedField):
    def get_url(self, obj, view_name, request, format):
        kwargs = {'account': obj.account, 'slug': obj.slug}
        return reverse(view_name, kwargs=kwargs, request=request, format=format)

    def get_object(self, queryset, view_name, view_args, view_kwargs):
        account = view_kwargs['account']
        slug = view_kwargs['slug']
        return queryset.get(account=account, slug=slug)
</code></pre>
<hr />
<h2 id="deprecated-apis">Deprecated APIs</h2>
<p>The following classes have been deprecated, in favor of the <code>many=&lt;bool&gt;</code> syntax.
They continue to function, but their usage will raise a <code>PendingDeprecationWarning</code>, which is silent by default.</p>
<ul>
<li><code>ManyRelatedField</code></li>
<li><code>ManyPrimaryKeyRelatedField</code></li>
<li><code>ManyHyperlinkedRelatedField</code></li>
<li><code>ManySlugRelatedField</code></li>
</ul>
<p>The <code>null=&lt;bool&gt;</code> flag has been deprecated in favor of the <code>required=&lt;bool&gt;</code> flag.  It will continue to function, but will raise a <code>PendingDeprecationWarning</code>.</p>
<p>In the 2.3 release, these warnings will be escalated to a <code>DeprecationWarning</code>, which is loud by default.
In the 2.4 release, these parts of the API will be removed entirely.</p>
<p>For more details see the <a href="../topics/2.2-announcement">2.2 release announcement</a>.</p>
<hr />
<h1 id="third-party-packages">Third Party Packages</h1>
<p>The following third party packages are also available.</p>
<h2 id="drf-nested-routers">DRF Nested Routers</h2>
<p>The <a href="https://github.com/alanjds/drf-nested-routers">drf-nested-routers package</a> provides routers and relationship fields for working with nested resources.</p>
          </div><!--/span-->
        </div><!--/row-->
      </div><!--/.fluid-container-->
    </div><!--/.body content-->

      <div id="push"></div>
  </div><!--/.wrapper -->

  <footer class="span12">
    <p>Sponsored by <a href="http://dabapps.com/">DabApps</a>.</a></p>
  </footer>

    <!-- Le javascript
    ================================================== -->
    <!-- Placed at the end of the document so the pages load faster -->
    <script src="http://www.django-rest-framework.org/js/jquery-1.8.1-min.js"></script>
    <script src="http://www.django-rest-framework.org/js/prettify-1.0.js"></script>
    <script src="http://www.django-rest-framework.org/js/bootstrap-2.1.1-min.js"></script>

    <script>
      //$('.side-nav').scrollspy()
      var shiftWindow = function() { scrollBy(0, -50) };
      if (location.hash) shiftWindow();
      window.addEventListener("hashchange", shiftWindow);

      $('.dropdown-menu').on('click touchstart', function(event) {
        event.stopPropagation();
      });

      // Dynamically force sidenav to no higher than browser window
      $('.side-nav').css('max-height', window.innerHeight - 130);

      $(function(){
        $(window).resize(function(){
          $('.side-nav').css('max-height', window.innerHeight - 130);
        });
      });
    </script>
</body></html>