Botond Botond - 6 months ago 10
Python Question

Django REST replace empty to default

I have a Django REST API set up and it works properly for valid incoming requests. In some of the requests, some of the fields are empty. Is there a way to provide default replacement values for those empty fields in the serializer, so that they would pass the validation test? For example, I have the following serializer:

class SearchRequestSerializer(serializers.ModelSerializer):

myfield1 = serializers.DecimalField(max_digits=10, decimal_places=2, coerce_to_string=False, default=0, required=False, allow_null=True)
class Meta:
model = SearchRequest
fields = ('myfield0', 'myfield1')


myfield1 is sometimes not provided. As shown above, I tried to default it to 0, but still getting

"myfield1":["A valid number is required."]


I don't know if it has any impact, but my requests are arrays and I'm using the serializer with the option many=True.

An example incomplete request would look like:

[{"myfield0":3, "myfield1":""}, {"myfield0":4, "myfield1":5}]

Answer

You are having this error because 0 is not decimal. Try default=0.0 or default=None

Update

An example incomplete request would look like:

[{"myfield0":3, "myfield1":""}, {"myfield0":4, "myfield1":5}]

Problem here is that you are supplying myfield1 as empty strings "myfield1": "". Your request should look like this.

[{"myfield0":3}, {"myfield0":4, "myfield1":5}]

If there is no value for myfield1 just don't put it in request. Otherwise you have to supply data which at least matches type. Because when field is not empty DRF does validation on it, default is used only when there is no value for field in submitted request.

http://www.django-rest-framework.org/api-guide/fields/#default