Django Rest Framework “A valid integer is required

2019-06-24 04:48发布

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?

1条回答
乱世女痞
2楼-- · 2019-06-24 05:25

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')
查看更多
登录 后发表回答