我希望在反序列化期间将空字符串默认为0或null。
JSON
{
'injuries': '6',
'children': '2',
'civilians': '',
}
但是,我一直收到这个错误:
"需要一个有效的整数。"
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)
主
serializer = StrikeSerializer(data=strike)
我尝试在create方法中操作数据,但在此之前会出现错误。在DRF结构中我可以覆盖它,特别是转换''为0还是无?
答案 0 :(得分:7)
您可以使用CharField
,然后在验证方法中转换为int
。
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')
答案 1 :(得分:3)
您可以使用 to_internal_value 方法在验证数据之前对其进行拦截。
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)