django-rest-framework/api-guide/relations.html
2014-09-17 14:12:41 +01:00

624 lines
34 KiB
HTML

<!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>