我设置了Django REST API,它可以正常用于有效的传入请求。在某些请求中,某些字段为空。有没有办法为序列化器中的那些空字段提供默认替换值,以便它们通过验证测试?例如,我有以下序列化程序:
private void releaseCameraAndPreview() {
if (mCamera != null) {
mCamera.release();
mCamera = null;
}
}
有时不提供myfield1。如上所示,我试图将其默认为0,但仍然得到
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus" />
我不知道它是否有任何影响,但我的请求是数组,我使用序列化程序选项many = True。
示例不完整的请求如下:
class SearchRequestSerializer(serializers.ModelSerializer):
myfield1 = serializers.DecimalField(max_digits=10, decimal_places=2, coerce_to_string=False, default=0, required=False, allow_null=True)
class Meta:
model = SearchRequest
fields = ('myfield0', 'myfield1')
答案 0 :(得分:1)
您遇到此错误,因为0
不是小数。
试试default=0.0
或default=None
<强>更新强>
示例不完整的请求如下:
[{"myfield0":3, "myfield1":""}, {"myfield0":4, "myfield1":5}]
问题在于您提供的myfield1
为空字符串"myfield1": ""
。您的请求应如下所示。
[{"myfield0":3}, {"myfield0":4, "myfield1":5}]
如果myfield1
没有价值,请不要将其放入请求中。否则,您必须提供至少与类型匹配的数据。因为当字段不为空时,DRF会对其进行验证,default
仅在提交的请求中没有字段值时使用。
http://www.django-rest-framework.org/api-guide/fields/#default