我按Django Rest Framework "A valid integer is required."?设置SpiderSerializer
,但似乎无法正常工作,仍然获得{"min_word_count":["A valid integer is required."]}
请求有效负载{..., min_word_count:""}
class Spider(models.Model):
...
min_word_count = models.PositiveIntegerField(
default=100,
null=True,
blank=True,
)
class SpiderSerializer(serializers.ModelSerializer):
min_word_count = serializers.IntegerField(default='', required=False)
class Meta:
model = Spider
exclude = ('category',)
def validate_min_word_count(self, value):
print('value1111111111111')
print(value)
if not value:
return 0
try:
value = int(value)
except ValueError:
raise serializers.ValidationError('You must supply an integer')
return value
答案 0 :(得分:1)
min_word_count:""
是一个空字符串,因此不是有效数字。
您可以min_word_count: None
并将allow_null=True
添加到字段声明中。
In [7]: class SpiderSerializer(serializers.Serializer):
...: min_word_count = serializers.IntegerField(default='', required=False)
...:
In [8]: s = SpiderSerializer(data={})
In [9]: s.is_valid()
Out[9]: True
In [10]: s = SpiderSerializer(data={'min_word_count': None})
In [11]: s.is_valid()
Out[11]: False
In [12]: s.errors
Out[12]:
ReturnDict([('min_word_count',
[ErrorDetail(string='This field may not be null.', code='null')])])
In [13]: s = SpiderSerializer(data={'min_word_count': ""})
In [14]: s.is_valid()
Out[14]: False
In [15]: s.errors
Out[15]:
ReturnDict([('min_word_count',
[ErrorDetail(string='A valid integer is required.', code='invalid')])])