Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ModelSerializer field validation for empty string

I'm having a problem with django rest framework.
My front is posting data to drf, and one of the fields could be null or an empty string "".

# 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')

publication_time could either be blank or "".

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

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

I've tried to add a field validator to the serializer class:

def validate_publication_time(self, value):
    if not value:
        return None

Or even using the extra_kwargs

# ....
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]} }

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.

PROBLEM:
The problem is that the validate_publication_time is never called and I get a validation error before even hitting the function. As I've understood there is a specific order in which the validators run, but now I have no idea how to solve my issue.

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

EDIT: This is the representation of my serializer:

# 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)

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

like image 668
Leonardo Avatar asked Dec 01 '22 16:12

Leonardo


1 Answers

I had the same problem and finally found a solution.

In order to deal with '' before the error occurs, you need to override the to_internal_value method:

class BookSerializer(serializers.ModelSerializer):
    def to_internal_value(self, data):
        if data.get('publication_time', None) == '':
            data.pop('publication_time')
        return super(BookSerializer, self).to_internal_value(data)
like image 199
Ivan Blinov Avatar answered Dec 04 '22 04:12

Ivan Blinov