我在我的DataSerliazer
中有一個自定義驗證函數,它檢查兩個參數(mrange,mthreshold)。驗證功能檢查發佈時只需設置其中一個參數。Django Rest框架:對HTTP POST和PUT的不同驗證
class DataSerializer(serializers.ModelSerializer):
emails = serializers.ListField(child = serializers.EmailField())
class Meta:
model = AIData
fields = ('id', 'name', 'created', 'username', 'token',
'expression','key','threshold' ,'evaluator', 'range','emails','metric_name', 'status')
def validate(self,attrs):
mrange = attrs.get("metric_range")
mthreshold = attrs.get("metric_threshold")
if (mrange == None or mrange == " ") and (mthreshold == None or mthreshold == " "):
raise serializers.ValidationError({'error': 'Cannot have both range and threshold empty'})
elif mrange != None and mthreshold != None:
raise serializers.ValidationError({'error': 'Cannot set both range and threshold'})
在我views.py文件
@api_view(['GET','PUT', 'DELETE'])
def ai_detail(request, token, id):
ai = None
try:
ai = AIData.objects.get(id=id)
except AIData.DoesNotExist:
return Response(status=status.HTTP_404_NOT_FOUND)
if request.method == 'GET':
serializer = DataSerializer(ai)
if serializer.data['token'] == token:
return Response(serializer.data)
else:
return Response({'error': 'Not allowed to access'}, status=status.HTTP_400_BAD_REQUEST)
elif request.method == 'PUT':
serializer = AlAnotherSerializerMethod(alert, data=request.data, partial=True)
if serializer.is_valid():
// updating code
目前,我必須寫anthor AIAnotherSerializerMethod
,這樣,它不隱式調用DataSerializer的驗證功能。這是爲了避免在創建對象時檢查2個參數。一旦對象被創建,我不想再檢查相同的功能。有沒有更好的方法來做同樣的事情?我最好避免爲同一模型編寫2個串行器。