2016-09-02 51 views
1

我有一個使用Django REST框架作爲資源公開的模型。 我需要在相關端點上執行POST請求時手動創建對象,這就是爲什麼我使用generics.ListCreateAPIView並覆蓋create()方法。何時以及如何使用Django REST框架驗證數據

不過,我需要檢查在POST請求的有效負載中給出的參數都能很好地形成/現有/ etc ...

我應該在哪裏執行此驗證,以及如何將其與串行相關?

我試圖在相關的串行器中編寫validate()方法,但它永遠不會被POST請求調用。

class ProductOrderList(generics.ListCreateAPIView): 
    model = ProductOrder 
    serializer_class = ProductOrderSerializer 
    queryset = ProductOrder.objects.all() 

    def create(self, request, *args, **kwargs): 
      data = request.data 
      # Some code here to prepare the manual creation of a 'ProductOrder' from the data 
      # I would like the validation happens here (or even before) 
      po = ProductOrder.objects.create(...) 


class ProductOrderSerializer(serializers.ModelSerializer): 

    class Meta: 
     model = ProductOrder 

    def validate(self, data): # Never called 
     # Is it the good place to write the validator ?? 

回答

4

下面是您overrided的創建方法的實現,從mixins.CreateModelMixin類採取:

def create(self, request, *args, **kwargs): 
    serializer = self.get_serializer(data=request.data) 
    serializer.is_valid(raise_exception=True) 
    self.perform_create(serializer) 
    headers = self.get_success_headers(serializer.data) 
    return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers) 

正如你所看到的,它就會被序列化,驗證數據和執行的創建對象來自序列化器驗證的數據。

如果您需要手動控制對象的創建,perform_create是您需要覆蓋的鉤子,而不是create

def perform_create(self, serializer): 
    # At this, the data is validated, you can do what you want 
    # by accessing serializer.validated_data 
+0

謝謝塞巴斯蒂安,它的作品就像一個魅力! – matt

相關問題