2016-01-05 66 views
2

我在我的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個串行器。

回答

0

你可以通過context data到串行其中可能包括請求本身。

您可以通過調用self.context隨時訪問序列化程序中任何位置的上下文。

該解決方案確實可以更輕鬆地提供上下文數據,而不會覆蓋__init__

0

就我所知,rest-framework庫沒有這樣的東西。

我這樣做的方式是覆蓋__init__並添加自己的變量來檢查這一點。

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 __init__(self, *args, **kwargs): 
     super(DataSerializer, self).__init__(*args, **kwargs) 
     self._request_method = kwargs.get('request_method', 'GET') 

    def validate(self,attrs): 
     if self._request_method == 'GET': 
      # GET logic 
     elif self._request_method in ('PUT', 'POST'): 
      # Put or Post logic 

然後我會使用這樣的:

serializer = DataSerializer(ai, request_method=request.method)