django-rest-framework/api-guide/relations/index.html
2021-03-25 12:24:20 +00:00

1071 lines
50 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="../../img/favicon.ico" rel="icon" type="image/x-icon">
<link rel="canonical" href="https://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">
<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>
#sidebarInclude img {
margin-bottom: 10px;
}
#sidebarInclude a.promo {
color: black;
}
@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/encode/django-rest-framework/tree/master">GitHub</a>
<a class="repo-link btn btn-inverse btn-small " rel="next" href="../validators/">
Next <i class="icon-arrow-right icon-white"></i>
</a>
<a class="repo-link btn btn-inverse btn-small " rel="prev" href="../fields/">
<i class="icon-arrow-left icon-white"></i> Previous
</a>
<a id="search_modal_show" class="repo-link btn btn-inverse btn-small" href="#mkdocs_search_modal" data-toggle="modal" data-target="#mkdocs_search_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="https://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="../caching/">Caching</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="../schemas/">Schemas</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/api-clients/">API Clients</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/html-and-forms/">HTML & Forms</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>
</ul>
</li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Community <b class="caret"></b></a>
<ul class="dropdown-menu">
<li >
<a href="../../community/tutorials-and-resources/">Tutorials and Resources</a>
</li>
<li >
<a href="../../community/third-party-packages/">Third Party Packages</a>
</li>
<li >
<a href="../../community/contributing/">Contributing to REST framework</a>
</li>
<li >
<a href="../../community/project-management/">Project management</a>
</li>
<li >
<a href="../../community/release-notes/">Release Notes</a>
</li>
<li >
<a href="../../community/3.12-announcement/">3.12 Announcement</a>
</li>
<li >
<a href="../../community/3.11-announcement/">3.11 Announcement</a>
</li>
<li >
<a href="../../community/3.10-announcement/">3.10 Announcement</a>
</li>
<li >
<a href="../../community/3.9-announcement/">3.9 Announcement</a>
</li>
<li >
<a href="../../community/3.8-announcement/">3.8 Announcement</a>
</li>
<li >
<a href="../../community/3.7-announcement/">3.7 Announcement</a>
</li>
<li >
<a href="../../community/3.6-announcement/">3.6 Announcement</a>
</li>
<li >
<a href="../../community/3.5-announcement/">3.5 Announcement</a>
</li>
<li >
<a href="../../community/3.4-announcement/">3.4 Announcement</a>
</li>
<li >
<a href="../../community/3.3-announcement/">3.3 Announcement</a>
</li>
<li >
<a href="../../community/3.2-announcement/">3.2 Announcement</a>
</li>
<li >
<a href="../../community/3.1-announcement/">3.1 Announcement</a>
</li>
<li >
<a href="../../community/3.0-announcement/">3.0 Announcement</a>
</li>
<li >
<a href="../../community/kickstarter-announcement/">Kickstarter Announcement</a>
</li>
<li >
<a href="../../community/mozilla-grant/">Mozilla Grant</a>
</li>
<li >
<a href="../../community/funding/">Funding</a>
</li>
<li >
<a href="../../community/jobs/">Jobs</a>
</li>
</ul>
</li>
</ul>
</div>
<!--/.nav-collapse -->
</div>
</div>
</div>
<div class="body-content">
<div class="container-fluid">
<!-- Search Modal -->
<div id="mkdocs_search_modal" 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">
<form role="form" autocomplete="off">
<div class="form-group">
<input type="text" name="q" class="form-control" placeholder="Search..." id="mkdocs-search-query">
</div>
</form>
<div id="mkdocs-search-results"></div>
</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">
<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-relationships">Inspecting 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>
<a href="#writable-nested-serializers">Writable nested serializers</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="#custom-hyperlinked-fields">Custom hyperlinked fields</a>
</li>
<li>
<a href="#example_2">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="#customizing-the-html-display">Customizing the HTML display</a>
</li>
<li>
<a href="#select-field-cutoffs">Select field cutoffs</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 class="main">
<a href="#third-party-packages">Third Party Packages</a>
</li>
<li>
<a href="#drf-nested-routers">DRF Nested Routers</a>
</li>
<li>
<a href="#rest-framework-generic-relations">Rest Framework Generic Relations</a>
</li>
<div class="promo">
<hr/>
<div id="sidebarInclude">
</div>
</ul>
</div>
</div>
<div id="main-content" class="span9">
<a class="github" href="https://github.com/encode/django-rest-framework/tree/master/rest_framework/relations.py">
<span class="label label-info">relations.py</span>
</a>
<h1 id="serializer-relations"><a class="toclink" href="#serializer-relations">Serializer relations</a></h1>
<blockquote>
<p>Data structures, not algorithms, are central to programming.</p>
<p>&mdash; <a href="http://users.ece.utexas.edu/~adnan/pike.html">Rob Pike</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-relationships"><a class="toclink" href="#inspecting-relationships">Inspecting relationships.</a></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))
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"><a class="toclink" href="#api-reference">API Reference</a></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', on_delete=models.CASCADE)
order = models.IntegerField()
title = models.CharField(max_length=100)
duration = models.IntegerField()
class Meta:
unique_together = ['album', 'order']
ordering = ['order']
def __str__(self):
return '%d: %s' % (self.order, self.title)
</code></pre>
<h2 id="stringrelatedfield"><a class="toclink" href="#stringrelatedfield">StringRelatedField</a></h2>
<p><code>StringRelatedField</code> may be used to represent the target of the relationship using its <code>__str__</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"><a class="toclink" href="#primarykeyrelatedfield">PrimaryKeyRelatedField</a></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': 'Undun',
'artist': 'The Roots',
'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>
<li><code>pk_field</code> - Set to a field to control serialization/deserialization of the primary key's value. For example, <code>pk_field=UUIDField(format='hex')</code> would serialize a UUID primary key into its compact hex representation.</li>
</ul>
<h2 id="hyperlinkedrelatedfield"><a class="toclink" href="#hyperlinkedrelatedfield">HyperlinkedRelatedField</a></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>
<hr />
<p><strong>Note</strong>: This field is designed for objects that map to a URL that accepts a single URL keyword argument, as set using the <code>lookup_field</code> and <code>lookup_url_kwarg</code> arguments.</p>
<p>This is suitable for URLs that contain a single primary key or slug argument as part of the URL.</p>
<p>If you require more complex hyperlinked representation you'll need to customize the field, as described in the <a href="#custom-hyperlinked-fields">custom hyperlinked fields</a> section, below.</p>
<hr />
<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="https://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"><a class="toclink" href="#slugrelatedfield">SlugRelatedField</a></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"><a class="toclink" href="#hyperlinkedidentityfield">HyperlinkedIdentityField</a></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="https://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"><a class="toclink" href="#nested-relationships">Nested relationships</a></h1>
<p>As opposed to previously discussed <em>references</em> to another entity, the referred entity can instead also be embedded or <em>nested</em>
in the representation of the object that refers to it.
Such 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"><a class="toclink" href="#example">Example</a></h2>
<p>For example, the following serializer:</p>
<pre><code>class TrackSerializer(serializers.ModelSerializer):
class Meta:
model = Track
fields = ['order', 'title', 'duration']
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>&gt;&gt;&gt; album = Album.objects.create(album_name="The Grey Album", artist='Danger Mouse')
&gt;&gt;&gt; Track.objects.create(album=album, order=1, title='Public Service Announcement', duration=245)
&lt;Track: Track object&gt;
&gt;&gt;&gt; Track.objects.create(album=album, order=2, title='What More Can I Say', duration=264)
&lt;Track: Track object&gt;
&gt;&gt;&gt; Track.objects.create(album=album, order=3, title='Encore', duration=159)
&lt;Track: Track object&gt;
&gt;&gt;&gt; serializer = AlbumSerializer(instance=album)
&gt;&gt;&gt; serializer.data
{
'album_name': 'The Grey Album',
'artist': 'Danger Mouse',
'tracks': [
{'order': 1, 'title': 'Public Service Announcement', 'duration': 245},
{'order': 2, 'title': 'What More Can I Say', 'duration': 264},
{'order': 3, 'title': 'Encore', 'duration': 159},
...
],
}
</code></pre>
<h2 id="writable-nested-serializers"><a class="toclink" href="#writable-nested-serializers">Writable nested serializers</a></h2>
<p>By default nested serializers are read-only. If you want to support write-operations to a nested serializer field you'll need to create <code>create()</code> and/or <code>update()</code> methods in order to explicitly specify how the child relationships should be saved:</p>
<pre><code>class TrackSerializer(serializers.ModelSerializer):
class Meta:
model = Track
fields = ['order', 'title', 'duration']
class AlbumSerializer(serializers.ModelSerializer):
tracks = TrackSerializer(many=True)
class Meta:
model = Album
fields = ['album_name', 'artist', 'tracks']
def create(self, validated_data):
tracks_data = validated_data.pop('tracks')
album = Album.objects.create(**validated_data)
for track_data in tracks_data:
Track.objects.create(album=album, **track_data)
return album
&gt;&gt;&gt; data = {
'album_name': 'The Grey Album',
'artist': 'Danger Mouse',
'tracks': [
{'order': 1, 'title': 'Public Service Announcement', 'duration': 245},
{'order': 2, 'title': 'What More Can I Say', 'duration': 264},
{'order': 3, 'title': 'Encore', 'duration': 159},
],
}
&gt;&gt;&gt; serializer = AlbumSerializer(data=data)
&gt;&gt;&gt; serializer.is_valid()
True
&gt;&gt;&gt; serializer.save()
&lt;Album: Album object&gt;
</code></pre>
<hr />
<h1 id="custom-relational-fields"><a class="toclink" href="#custom-relational-fields">Custom relational fields</a></h1>
<p>In rare cases where none of the existing relational styles fit the representation you need,
you can implement a completely custom relational field, that describes exactly how the
output representation should be generated from the model instance.</p>
<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 <a href="https://www.django-rest-framework.org/api-guide/serializers/#to_internal_valueself-data"><code>.to_internal_value(self, data)</code> method</a>.</p>
<p>To provide a dynamic queryset based on the <code>context</code>, you can also override <code>.get_queryset(self)</code> instead of specifying <code>.queryset</code> on the class or when initializing the field.</p>
<h2 id="example_1"><a class="toclink" href="#example_1">Example</a></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="custom-hyperlinked-fields"><a class="toclink" href="#custom-hyperlinked-fields">Custom hyperlinked fields</a></h1>
<p>In some cases you may need to customize the behavior of a hyperlinked field, in order to represent URLs that require more than a single lookup field.</p>
<p>You can achieve this by overriding <code>HyperlinkedRelatedField</code>. There are two methods that may be overridden:</p>
<p><strong>get_url(self, obj, view_name, request, format)</strong></p>
<p>The <code>get_url</code> method is used to map the object instance to its URL representation.</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>
<p><strong>get_object(self, view_name, view_args, view_kwargs)</strong></p>
<p>If you want to support a writable hyperlinked field then you'll also want to override <code>get_object</code>, in order to map incoming URLs back to the object they represent. For read-only hyperlinked fields there is no need to override this method.</p>
<p>The return value of this method should the object that corresponds to the matched URL conf arguments.</p>
<p>May raise an <code>ObjectDoesNotExist</code> exception.</p>
<h2 id="example_2"><a class="toclink" href="#example_2">Example</a></h2>
<p>Say we have a URL for a customer object that takes two keyword arguments, like so:</p>
<pre><code>/api/&lt;organization_slug&gt;/customers/&lt;customer_pk&gt;/
</code></pre>
<p>This cannot be represented with the default implementation, which accepts only a single lookup field.</p>
<p>In this case we'd need to override <code>HyperlinkedRelatedField</code> to get the behavior we want:</p>
<pre><code>from rest_framework import serializers
from rest_framework.reverse import reverse
class CustomerHyperlink(serializers.HyperlinkedRelatedField):
# We define these as class attributes, so we don't need to pass them as arguments.
view_name = 'customer-detail'
queryset = Customer.objects.all()
def get_url(self, obj, view_name, request, format):
url_kwargs = {
'organization_slug': obj.organization.slug,
'customer_pk': obj.pk
}
return reverse(view_name, kwargs=url_kwargs, request=request, format=format)
def get_object(self, view_name, view_args, view_kwargs):
lookup_kwargs = {
'organization__slug': view_kwargs['organization_slug'],
'pk': view_kwargs['customer_pk']
}
return self.get_queryset().get(**lookup_kwargs)
</code></pre>
<p>Note that if you wanted to use this style together with the generic views then you'd also need to override <code>.get_object</code> on the view in order to get the correct lookup behavior.</p>
<p>Generally we recommend a flat style for API representations where possible, but the nested URL style can also be reasonable when used in moderation.</p>
<hr />
<h1 id="further-notes"><a class="toclink" href="#further-notes">Further notes</a></h1>
<h2 id="the-queryset-argument"><a class="toclink" href="#the-queryset-argument">The <code>queryset</code> argument</a></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="customizing-the-html-display"><a class="toclink" href="#customizing-the-html-display">Customizing the HTML display</a></h2>
<p>The built-in <code>__str__</code> method of the model will be used to generate string representations of the objects used to populate the <code>choices</code> property. These choices are used to populate select HTML inputs in the browsable API.</p>
<p>To provide customized representations for such inputs, override <code>display_value()</code> of a <code>RelatedField</code> subclass. This method will receive a model object, and should return a string suitable for representing it. For example:</p>
<pre><code>class TrackPrimaryKeyRelatedField(serializers.PrimaryKeyRelatedField):
def display_value(self, instance):
return 'Track: %s' % (instance.title)
</code></pre>
<h2 id="select-field-cutoffs"><a class="toclink" href="#select-field-cutoffs">Select field cutoffs</a></h2>
<p>When rendered in the browsable API relational fields will default to only displaying a maximum of 1000 selectable items. If more items are present then a disabled option with "More than 1000 items…" will be displayed.</p>
<p>This behavior is intended to prevent a template from being unable to render in an acceptable timespan due to a very large number of relationships being displayed.</p>
<p>There are two keyword arguments you can use to control this behavior:</p>
<ul>
<li><code>html_cutoff</code> - If set this will be the maximum number of choices that will be displayed by a HTML select drop down. Set to <code>None</code> to disable any limiting. Defaults to <code>1000</code>.</li>
<li><code>html_cutoff_text</code> - If set this will display a textual indicator if the maximum number of items have been cutoff in an HTML select drop down. Defaults to <code>"More than {count} items…"</code></li>
</ul>
<p>You can also control these globally using the settings <code>HTML_SELECT_CUTOFF</code> and <code>HTML_SELECT_CUTOFF_TEXT</code>.</p>
<p>In cases where the cutoff is being enforced you may want to instead use a plain input field in the HTML form. You can do so using the <code>style</code> keyword argument. For example:</p>
<pre><code>assigned_to = serializers.SlugRelatedField(
queryset=User.objects.all(),
slug_field='username',
style={'base_template': 'input.html'}
)
</code></pre>
<h2 id="reverse-relations"><a class="toclink" href="#reverse-relations">Reverse relations</a></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', on_delete=models.CASCADE)
...
</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/stable/topics/db/queries/#following-relationships-backward">reverse relationships</a> for more details.</p>
<h2 id="generic-relationships"><a class="toclink" href="#generic-relationships">Generic relationships</a></h2>
<p>If you want to serialize a generic foreign key, you need to define a custom field, to determine explicitly how you want to serialize the targets of the relationship.</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/stable/ref/contrib/contenttypes/
"""
tag_name = models.SlugField()
content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
object_id = models.PositiveIntegerField()
tagged_object = GenericForeignKey('content_type', 'object_id')
def __str__(self):
return self.tag_name
</code></pre>
<p>And the following two models, which may 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/stable/ref/contrib/contenttypes/#id1">the Django documentation on generic relations</a>.</p>
<h2 id="manytomanyfields-with-a-through-model"><a class="toclink" href="#manytomanyfields-with-a-through-model">ManyToManyFields with a Through Model</a></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>
<p>If you wish to represent <a href="https://docs.djangoproject.com/en/stable/topics/db/models/#intermediary-manytomany">extra fields on a through model</a> then you may serialize the through model as <a href="https://www.django-rest-framework.org/api-guide/serializers/#dealing-with-nested-objects">a nested object</a>.</p>
<hr />
<h1 id="third-party-packages"><a class="toclink" href="#third-party-packages">Third Party Packages</a></h1>
<p>The following third party packages are also available.</p>
<h2 id="drf-nested-routers"><a class="toclink" href="#drf-nested-routers">DRF Nested Routers</a></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>
<h2 id="rest-framework-generic-relations"><a class="toclink" href="#rest-framework-generic-relations">Rest Framework Generic Relations</a></h2>
<p>The <a href="https://github.com/Ian-Foote/rest-framework-generic-relations">rest-framework-generic-relations</a> library provides read/write serialization for generic foreign keys.</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>.
</p>
</footer>
<!-- Le javascript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script async src="https://fund.django-rest-framework.org/sidebar_include.js"></script>
<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>var base_url = '../..';</script>
<script src="../../search/main.js" defer></script>
<script>
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/dropdown to no higher than browser window
$('.side-nav, .dropdown-menu').css('max-height', window.innerHeight - 130);
$(function() {
$(window).resize(function() {
$('.side-nav, .dropdown-menu').css('max-height', window.innerHeight - 130);
});
});
</script>
</body>
</html>