Django Rest Framework "A valid integer is required."?
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')
You can use to_internal_value method to intercept the data before it is being validated.
class StrikeSerializer(serializers.ModelSerializer):
civilians = serializers.IntegerField(default=0, required=False)
class Meta:
model = Strike
fields = '__all__'
def to_internal_value(self, data):
if data.get('civilians') == '':
data['civilians'] = 0
return super(StrikeSerializer, self).to_internal_value(data)
def create(self, validated_data):
return Strike.objects.create(**validated_data)