<p>Most of the time you're dealing with validation in REST framework you'll simply be relying on the default field validation, or writing explicit validation methods on serializer or field classes.</p>
<p>However, sometimes you'll want to place your validation logic into reusable components, so that it can easily be reused throughout your codebase. This can be achieved by using validator functions and validator classes.</p>
<h2id="validation-in-rest-framework"><aclass="toclink"href="#validation-in-rest-framework">Validation in REST framework</a></h2>
<p>Validation in Django REST framework serializers is handled a little differently to how validation works in Django's <code>ModelForm</code> class.</p>
<p>With <code>ModelForm</code> the validation is performed partially on the form, and partially on the model instance. With REST framework the validation is performed entirely on the serializer class. This is advantageous for the following reasons:</p>
<ul>
<li>It introduces a proper separation of concerns, making your code behavior more obvious.</li>
<li>It is easy to switch between using shortcut <code>ModelSerializer</code> classes and using explicit <code>Serializer</code> classes. Any validation behavior being used for <code>ModelSerializer</code> is simple to replicate.</li>
<li>Printing the <code>repr</code> of a serializer instance will show you exactly what validation rules it applies. There's no extra hidden validation behavior being called on the model instance.</li>
</ul>
<p>When you're using <code>ModelSerializer</code> all of this is handled automatically for you. If you want to drop down to using <code>Serializer</code> classes instead, then you need to define the validation rules explicitly.</p>
<p>The interesting bit here is the <code>reference</code> field. We can see that the uniqueness constraint is being explicitly enforced by a validator on the serializer field.</p>
<p>Because of this more explicit style REST framework includes a few validator classes that are not available in core Django. These classes are detailed below. REST framework validators, like their Django counterparts, implement the <code>__eq__</code> method, allowing you to compare instances for equality.</p>
<p>This validator can be used to enforce <code>unique_together</code> constraints on model instances.
It has two required arguments, and a single optional <code>messages</code> argument:</p>
<ul>
<li><code>queryset</code><em>required</em> - This is the queryset against which uniqueness should be enforced.</li>
<li><code>fields</code><em>required</em> - A list or tuple of field names which should make a unique set. These must exist as fields on the serializer class.</li>
<li><code>message</code> - The error message that should be used when validation fails.</li>
</ul>
<p>The validator should be applied to <em>serializer classes</em>, like so:</p>
# ToDo items belong to a parent list, and have an ordering defined
#by the 'position' field. No two items in a given list may share
# the same position.
validators = [
UniqueTogetherValidator(
queryset=ToDoItem.objects.all(),
fields=['list', 'position']
)
]
</code></pre>
<hr/>
<p><strong>Note</strong>: The <code>UniqueTogetherValidator</code> class always imposes an implicit constraint that all the fields it applies to are always treated as required. Fields with <code>default</code> values are an exception to this as they always supply a value even when omitted from user input.</p>
<p>These validators can be used to enforce the <code>unique_for_date</code>, <code>unique_for_month</code> and <code>unique_for_year</code> constraints on model instances. They take the following arguments:</p>
<ul>
<li><code>queryset</code><em>required</em> - This is the queryset against which uniqueness should be enforced.</li>
<li><code>field</code><em>required</em> - A field name against which uniqueness in the given date range will be validated. This must exist as a field on the serializer class.</li>
<li><code>date_field</code><em>required</em> - A field name which will be used to determine date range for the uniqueness constrain. This must exist as a field on the serializer class.</li>
<li><code>message</code> - The error message that should be used when validation fails.</li>
</ul>
<p>The validator should be applied to <em>serializer classes</em>, like so:</p>
# Blog posts should have a slug that is unique for the current year.
validators = [
UniqueForYearValidator(
queryset=BlogPostItem.objects.all(),
field='slug',
date_field='published'
)
]
</code></pre>
<p>The date field that is used for the validation is always required to be present on the serializer class. You can't simply rely on a model class <code>default=...</code>, because the value being used for the default wouldn't be generated until after the validation has run.</p>
<p>There are a couple of styles you may want to use for this depending on how you want your API to behave. If you're using <code>ModelSerializer</code> you'll probably simply rely on the defaults that REST framework generates for you, but if you are using <code>Serializer</code> or simply want more explicit control, use on of the styles demonstrated below.</p>
<h4id="using-with-a-writable-date-field"><aclass="toclink"href="#using-with-a-writable-date-field">Using with a writable date field.</a></h4>
<p>If you want the date field to be writable the only thing worth noting is that you should ensure that it is always available in the input data, either by setting a <code>default</code> argument, or by setting <code>required=True</code>.</p>
<h4id="using-with-a-read-only-date-field"><aclass="toclink"href="#using-with-a-read-only-date-field">Using with a read-only date field.</a></h4>
<p>If you want the date field to be visible, but not editable by the user, then set <code>read_only=True</code> and additionally set a <code>default=...</code> argument.</p>
<h4id="using-with-a-hidden-date-field"><aclass="toclink"href="#using-with-a-hidden-date-field">Using with a hidden date field.</a></h4>
<p>If you want the date field to be entirely hidden from the user, then use <code>HiddenField</code>. This field type does not accept user input, but instead always returns its default value to the <code>validated_data</code> in the serializer.</p>
<p><strong>Note</strong>: The <code>UniqueFor<Range>Validator</code> classes impose an implicit constraint that the fields they are applied to are always treated as required. Fields with <code>default</code> values are an exception to this as they always supply a value even when omitted from user input.</p>
<p><strong>Note:</strong><code>HiddenField()</code> does not appear in <code>partial=True</code> serializer (when making <code>PATCH</code> request). This behavior might change in future, follow updates on <ahref="https://github.com/encode/django-rest-framework/discussions/8259">github discussion</a>. </p>
<h1id="advanced-field-defaults"><aclass="toclink"href="#advanced-field-defaults">Advanced field defaults</a></h1>
<p>Validators that are applied across multiple fields in the serializer can sometimes require a field input that should not be provided by the API client, but that <em>is</em> available as input to the validator.</p>
<p>Two patterns that you may want to use for this sort of validation include:</p>
<ul>
<li>Using <code>HiddenField</code>. This field will be present in <code>validated_data</code> but <em>will not</em> be used in the serializer output representation.</li>
<li>Using a standard field with <code>read_only=True</code>, but that also includes a <code>default=…</code> argument. This field <em>will</em> be used in the serializer output representation, but cannot be set directly by the user.</li>
</ul>
<p>REST framework includes a couple of defaults that may be useful in this context.</p>
<p>A default class that can be used to represent the current user. In order to use this, the 'request' must have been provided as part of the context dictionary when instantiating the serializer.</p>
<p>To write a class-based validator, use the <code>__call__</code> method. Class-based validators are useful as they allow you to parameterize and reuse behavior.</p>