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 use a
CharField
and then convert toint
in the validation method.