<!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="../../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">
  <meta name="author" content="Tom Christie">

  <!-- Le styles -->
  <link href="../../css/prettify.css" rel="stylesheet">
  <link href="../../css/bootstrap.css" rel="stylesheet">
  <link href="../../css/bootstrap-responsive.css" rel="stylesheet">
  <link href="../../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="-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 " rel="prev" href="../validators">
            Next <i class="icon-arrow-right icon-white"></i>
          </a>
          <a class="repo-link btn btn-inverse btn-small " rel="next" href="../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">
            
            <!-- Main navigation -->
            <ul class="nav navbar-nav">
              <li ><a href="/">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="../../tutorial/quickstart">Quickstart</a>
                  </li>
                  
                  <li >
                    <a href="../../tutorial/1-serialization">1 - Serialization</a>
                  </li>
                  
                  <li >
                    <a href="../../tutorial/2-requests-and-responses">2 - Requests and responses</a>
                  </li>
                  
                  <li >
                    <a href="../../tutorial/3-class-based-views">3 - Class based views</a>
                  </li>
                  
                  <li >
                    <a href="../../tutorial/4-authentication-and-permissions">4 - Authentication and permissions</a>
                  </li>
                  
                  <li >
                    <a href="../../tutorial/5-relationships-and-hyperlinked-apis">5 - Relationships and hyperlinked APIs</a>
                  </li>
                  
                  <li >
                    <a href="../../tutorial/6-viewsets-and-routers">6 - Viewsets and routers</a>
                  </li>
                  
                </ul>
              </li>
                
              <li class="dropdown active">
                <a href="#" class="dropdown-toggle" data-toggle="dropdown">API Guide <b class="caret"></b></a>
                <ul class="dropdown-menu">
                  
                  <li >
                    <a href="../requests">Requests</a>
                  </li>
                  
                  <li >
                    <a href="../responses">Responses</a>
                  </li>
                  
                  <li >
                    <a href="../views">Views</a>
                  </li>
                  
                  <li >
                    <a href="../generic-views">Generic views</a>
                  </li>
                  
                  <li >
                    <a href="../viewsets">Viewsets</a>
                  </li>
                  
                  <li >
                    <a href="../routers">Routers</a>
                  </li>
                  
                  <li >
                    <a href="../parsers">Parsers</a>
                  </li>
                  
                  <li >
                    <a href="../renderers">Renderers</a>
                  </li>
                  
                  <li >
                    <a href="../serializers">Serializers</a>
                  </li>
                  
                  <li >
                    <a href="../fields">Serializer fields</a>
                  </li>
                  
                  <li class="active" >
                    <a href=".">Serializer relations</a>
                  </li>
                  
                  <li >
                    <a href="../validators">Validators</a>
                  </li>
                  
                  <li >
                    <a href="../authentication">Authentication</a>
                  </li>
                  
                  <li >
                    <a href="../permissions">Permissions</a>
                  </li>
                  
                  <li >
                    <a href="../throttling">Throttling</a>
                  </li>
                  
                  <li >
                    <a href="../filtering">Filtering</a>
                  </li>
                  
                  <li >
                    <a href="../pagination">Pagination</a>
                  </li>
                  
                  <li >
                    <a href="../versioning">Versioning</a>
                  </li>
                  
                  <li >
                    <a href="../content-negotiation">Content negotiation</a>
                  </li>
                  
                  <li >
                    <a href="../metadata">Metadata</a>
                  </li>
                  
                  <li >
                    <a href="../format-suffixes">Format suffixes</a>
                  </li>
                  
                  <li >
                    <a href="../reverse">Returning URLs</a>
                  </li>
                  
                  <li >
                    <a href="../exceptions">Exceptions</a>
                  </li>
                  
                  <li >
                    <a href="../status-codes">Status codes</a>
                  </li>
                  
                  <li >
                    <a href="../testing">Testing</a>
                  </li>
                  
                  <li >
                    <a href="../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="../../topics/documenting-your-api">Documenting your API</a>
                  </li>
                  
                  <li >
                    <a href="../../topics/internationalization">Internationalization</a>
                  </li>
                  
                  <li >
                    <a href="../../topics/ajax-csrf-cors">AJAX, CSRF & CORS</a>
                  </li>
                  
                  <li >
                    <a href="../../topics/browser-enhancements">Browser enhancements</a>
                  </li>
                  
                  <li >
                    <a href="../../topics/browsable-api">The Browsable API</a>
                  </li>
                  
                  <li >
                    <a href="../../topics/rest-hypermedia-hateoas">REST, Hypermedia & HATEOAS</a>
                  </li>
                  
                  <li >
                    <a href="../../topics/third-party-resources">Third Party Resources</a>
                  </li>
                  
                  <li >
                    <a href="../../topics/contributing">Contributing to REST framework</a>
                  </li>
                  
                  <li >
                    <a href="../../topics/project-management">Project management</a>
                  </li>
                  
                  <li >
                    <a href="../../topics/3.0-announcement">3.0 Announcement</a>
                  </li>
                  
                  <li >
                    <a href="../../topics/3.1-announcement">3.1 Announcement</a>
                  </li>
                  
                  <li >
                    <a href="../../topics/kickstarter-announcement">Kickstarter Announcement</a>
                  </li>
                  
                  <li >
                    <a href="../../topics/release-notes">Release Notes</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>
                      <a href="#inspecting-automatically-generated-relationships">Inspecting automatically generated relationships.</a>
                    </li>
                  

                

                  <li class="main">
                    <a href="#api-reference">API Reference</a>
                  </li>

                  
                    <li>
                      <a href="#stringrelatedfield">StringRelatedField</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_1">Example</a>
                    </li>
                  

                

                  <li class="main">
                    <a href="#further-notes">Further notes</a>
                  </li>

                  
                    <li>
                      <a href="#the-queryset-argument">The queryset argument</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 class="main">
                    <a href="#third-party-packages">Third Party Packages</a>
                  </li>

                  
                    <li>
                      <a href="#drf-nested-routers">DRF Nested Routers</a>
                    </li>
                  

                

                

              </ul>

            </div>
          </div>

          <div id="main-content" class="span9">
            
              
                <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>
              
            

            <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 />
<h4 id="inspecting-automatically-generated-relationships">Inspecting automatically generated relationships.</h4>
<p>When using the <code>ModelSerializer</code> 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.</p>
<p>To do so, open the Django shell, using <code>python manage.py shell</code>, then import the serializer class, instantiate it, and print the object representation…</p>
<pre><code>&gt;&gt;&gt; from myapp.serializers import AccountSerializer
&gt;&gt;&gt; serializer = AccountSerializer()
&gt;&gt;&gt; print repr(serializer)  # Or `print(repr(serializer))` in Python 3.x.
AccountSerializer():
    id = IntegerField(label='ID', read_only=True)
    name = CharField(allow_blank=True, max_length=100, required=False)
    owner = PrimaryKeyRelatedField(queryset=User.objects.all())
</code></pre>
<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><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')
        ordering = ['order']

    def __unicode__(self):
        return '%d: %s' % (self.order, self.title)
</code></pre>
<h2 id="stringrelatedfield">StringRelatedField</h2>
<p><code>StringRelatedField</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><code>class AlbumSerializer(serializers.ModelSerializer):
    tracks = serializers.StringRelatedField(many=True)

    class Meta:
        model = Album
        fields = ('album_name', 'artist', 'tracks')
</code></pre>
<p>Would serialize to the following representation.</p>
<pre><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><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><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>queryset</code> - The queryset used for model instance lookups when validating the field input. Relationships must either set a queryset explicitly, or set <code>read_only=True</code>.</li>
<li><code>many</code> - If applied to a to-many relationship, you should set this argument to <code>True</code>.</li>
<li><code>allow_null</code> - If set to <code>True</code>, the field will accept values of <code>None</code> or the empty string for nullable relationships. Defaults to <code>False</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><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><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 will be a string with the format <code>&lt;modelname&gt;-detail</code>. <strong>required</strong>.</li>
<li><code>queryset</code> - The queryset used for model instance lookups when validating the field input. Relationships must either set a queryset explicitly, or set <code>read_only=True</code>.</li>
<li><code>many</code> - If applied to a to-many relationship, you should set this argument to <code>True</code>.</li>
<li><code>allow_null</code> - If set to <code>True</code>, the field will accept values of <code>None</code> or the empty string for nullable relationships. Defaults to <code>False</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>lookup_url_kwarg</code> - The name of the keyword argument defined in the URL conf that corresponds to the lookup field. Defaults to using the same value as <code>lookup_field</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><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><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>queryset</code> - The queryset used for model instance lookups when validating the field input. Relationships must either set a queryset explicitly, or set <code>read_only=True</code>.</li>
<li><code>many</code> - If applied to a to-many relationship, you should set this argument to <code>True</code>.</li>
<li><code>allow_null</code> - If set to <code>True</code>, the field will accept values of <code>None</code> or the empty string for nullable relationships. Defaults to <code>False</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><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><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 will 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>lookup_url_kwarg</code> - The name of the keyword argument defined in the URL conf that corresponds to the lookup field. Defaults to using the same value as <code>lookup_field</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><code>class TrackSerializer(serializers.ModelSerializer):
    class Meta:
        model = Track
        fields = ('order', 'title')

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

    class Meta:
        model = Album
        fields = ('album_name', 'artist', 'tracks')
</code></pre>
<p>Would serialize to a nested representation like this:</p>
<pre><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_representation(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. The <code>value</code> argument will typically be a model instance.</p>
<p>If you want to implement a read-write relational field, you must also implement the <code>.to_internal_value(self, data)</code> method.</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><code>import time

class TrackListingField(serializers.RelatedField):
    def to_representation(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><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="the-queryset-argument">The <code>queryset</code> argument</h2>
<p>The <code>queryset</code> argument is only ever required for <em>writable</em> 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.</p>
<p>In version 2.x a serializer class could <em>sometimes</em> automatically determine the <code>queryset</code> argument <em>if</em> a <code>ModelSerializer</code> class was being used.</p>
<p>This behavior is now replaced with <em>always</em> using an explicit <code>queryset</code> argument for writable relational fields.</p>
<p>Doing so reduces the amount of hidden 'magic' that <code>ModelSerializer</code> provides, makes the behavior of the field more clear, and ensures that it is trivial to move between using the <code>ModelSerializer</code> shortcut, or using fully explicit <code>Serializer</code> classes.</p>
<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><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><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><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><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><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><code>class TaggedObjectRelatedField(serializers.RelatedField):
    """
    A custom field to use for the `tagged_object` generic relationship.
    """

    def to_representation(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_representation()</code> method:</p>
<pre><code>    def to_representation(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><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 />
<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>Documentation built with <a href="http://www.mkdocs.org/">MkDocs</a>.</a>
    </p>
  </footer>

  <!-- Le javascript
  ================================================== -->
  <!-- Placed at the end of the document so the pages load faster -->
  <script src="../../js/jquery-1.8.1-min.js"></script>
  <script src="../../js/prettify-1.0.js"></script>
  <script src="../../js/bootstrap-2.1.1-min.js"></script>
  <script src="../../js/theme.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>