ModelSerializer field validation for empty string
<p>I'm having a problem with django rest framework.<br>
My front is posting data to drf, and one of the fields could be <code>null</code> or an empty string <code>""</code>. </p>

<pre><code># models.py
class Book(models.Model):
    title = models.CharField(max_length=100)
    publication_time = models.TimeField(null=True, blank=True)


# serializers.py
from rest_framework import serializers
from .models import Book

class BookSerializer(serializers.ModelSerializer):
    class Meta:
        model = Book
        fields = ('id', 'title', 'publication_time')
</code></pre>

<p><code>publication_time</code> could either be <code>blank</code> or <code>""</code>.    </p>

<p>The blank case works, in fact when I post a json <code>{"title": "yeah a book", "publication_time": none}</code> everything is fine.</p>

<p>When I send <code>{"title": "yeah a book", "publication_time":""}</code> I do get a validation error <code>"Time has wrong format. Use one of these formats instead: hh:mm[:ss[.uuuuuu]]."</code></p>

<p>I've tried to add a field validator to the serializer class:</p>

<pre><code>def validate_publication_time(self, value):
    if not value:
        return None
</code></pre>

<p>Or even using the extra_kwargs</p>

<pre><code># ....
def empty_string_to_none(value):
    if not value:
        return None    

# ....
class BookSerializer(serializers.ModelSerializer):
    class Meta:
        model = Book
        fields = ('id', 'title', 'publication_time')
        extra_kwargs = {'publication_time': {'validators' : [empty_string_to_none]} }
</code></pre>

<p>What I am trying to do is to transform an empty string to None (that should be accepted by the serializer and the model) before any validation occurs or as the first validation rule. </p>

<p><strong>PROBLEM:</strong><br>
The problem is that the <code>validate_publication_time</code> is never called and I get a validation error before even hitting the function. As I've <a href="https://stackoverflow.com/a/27591842/1191416">understood</a> there is a specific order in which the validators run, but now I have no idea how to solve my issue.  </p>

<p><strong>QUESTION:</strong><br>
What I want to do is to actually clean the data in order to transform <code>""</code> into <code>None</code> before any validation is run. Is it possible? How?</p>

<p><strong>EDIT:</strong>
This is the representation of my serializer:</p>

<pre><code># from myapp.serializers import BookSerializer
# serializer = BookSerializer()
# print repr(serializer)
# This is the print result:
BookSerializer():
    id = IntegerField(label='ID', read_only=True)
    title = CharField(max_length=100)
    publication_time = TimeField(allow_null=True, required=False)
</code></pre>

<p>So as you can see the publication_time field could be null, isn't it?</p>