<metaname="description"content="Django, API, REST, Serializer relations, API Reference, Nested relationships, Custom relational fields, Further notes, Third Party Packages">
<divclass="clear"><inputclass="btn btn-success"type="submit"value="Yes, keep me posted!"name="subscribe"id="mc-embedded-subscribe"class="button"></div>
<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.<FieldName></code>.</p>
<hr/>
<h1id="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>
<p>Would serialize to a representation like this:</p>
<preclass="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>
<p>Would serialize to a representation like this:</p>
<preclass="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. <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>
<h2id="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>Would serialize to a representation like this:</p>
<preclass="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>
<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>
<li><code>view_name</code> - The view name that should be used as the target of the relationship. <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>
<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>
<h2id="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>
<preclass="prettyprint lang-py"><code>import time
class TrackListingField(serializers.RelatedField):
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>
<preclass="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/>
<h1id="further-notes">Further notes</h1>
<h2id="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>
<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>
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>
<p>See the Django documentation on <ahref="https://docs.djangoproject.com/en/dev/topics/db/queries/#following-relationships-backward">reverse relationships</a> for more details.</p>
<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>
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>
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>
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 <ahref="https://docs.djangoproject.com/en/dev/ref/contrib/contenttypes/#id1">the Django documentation on generic relations</a>.</p>
<h2id="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>
<p>This method should the object that corresponds to the matched URL conf arguments.</p>
<p>May raise an <code>ObjectDoesNotExist</code> exception.</p>
<h3id="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>
<p>The following classes have been deprecated, in favor of the <code>many=<bool></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=<bool></code> flag has been deprecated in favor of the <code>required=<bool></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>The <ahref="https://github.com/alanjds/drf-nested-routers">drf-nested-routers package</a> provides routers and relationship fields for working with nested resources.</p>