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?
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With