I want to default an empty string to a 0 or null during deserialization.
JSON
{
'injuries': '6',
'children': '2',
'civilians': '',
}
However, I keep getting this error:
"A valid integer is required."
models.py
from django.db import models
class Strike(models.Model):
location = models.ForeignKey('Location', on_delete=models.CASCADE)
civilians = models.PositiveIntegerField(blank=True, null=True)
injuries = models.PositiveIntegerField(blank=True, null=True)
children = models.PositiveIntegerField(blank=True, null=True)
serializers.py
from rest_framework import serializers
from .models import Strike
class StrikeSerializer(serializers.ModelSerializer):
civilians = serializers.IntegerField(default=0, required=False)
class Meta:
model = Strike
fields = '__all__'
def create(self, validated_data):
return Strike.objects.create(**validated_data)
main
serializer = StrikeSerializer(data=strike)
I tried manipulating data in create method, but the error gets raised before that. Where in the DRF structure can I override this, specifically convert '' to 0 or None?
You can implement custom exception handling by creating a handler function that converts exceptions raised in your API views into response objects. This allows you to control the style of error responses used by your API.
read_only. Read-only fields are included in the API output, but should not be included in the input during create or update operations. Any 'read_only' fields that are incorrectly included in the serializer input will be ignored.
Serializer Method Field This is a read-only field. It gets its value by calling a method on the serializer class it is attached to. It can be used to add any sort of data to the serialized representation of your object. SerializerMethodField gets its data by calling get_<field_name> .
You can use a CharField
and then convert to int
in the validation method.
class StrikeSerializer(serializers.ModelSerializer):
civilians = serializers.CharField(
required=False, allow_null=True, allow_blank=True)
def validate_civilians(self, value):
if not value:
return 0
try:
return int(value)
except ValueError:
raise serializers.ValidationError('You must supply an integer')
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