2014-12-29 67 views

回答

3

我知道我需要嘗試/除了一些東西塊,但我不知道什麼。我查看了DRF代碼,並且看到那個generics.ListCreateAPIView有一個名爲的方法創建。我在我的班級裏寫了一個名爲父創建的新函數,它與我繼承的簽名相同,其名稱爲創建,我將try/except放在此函數的周圍。

最後,它看起來是這樣的:

class MyModelList(generics.ListCreateAPIView): 
    def get_queryset(self): 
     return MyModel.objects.all() 
    def create(self, request, *args, **kwargs): 
     try: 
      return super(MyModelList, self).create(request, *args, **kwargs) 
     except IntegrityError: 
      raise CustomUniqueException 
    serializer_class = MyModelSerializer 

我希望這可以幫助別人。

+0

雖然這種方法可行,但如果你發現自己經常重複,你最好通過@ Cartucho關於使用定製異常處理程序 –

1

如果你想要這個只爲這一觀點覆蓋handle_exception

class MyAPIView(APIView): 
    ... 

    def handle_exception(self, exc): 
     """ 
     Handle any exception that occurs, by returning an appropriate 
     response,or re-raising the error. 
     """ 
     ... 

要處理它所有視圖,你可以定義一個全局異常處理程序,在這裏看到:http://www.django-rest-framework.org/api-guide/exceptions

相關問題