2017-04-13 63 views
1

假設使用person模型,ModelSerializer和相應ReadOnlyModelViewSet的最小應用程序。請求/person/1響應時在數據庫自定義NotFound異常--- Django REST框架

只有一個項目存在這樣正確的是:

{ 
    "name": "RandomName1" 
} 

當請求/person/2的迴應是:

{ 
    "detail": "Not found." 
} 

我想定製的。

儘管我讀了documentation,但我不清楚該如何定製此功能。

我應該澄清,我正在尋找定製這個,根據該觀點。例如/person/2應該返回:

{ 
    "detail": "Person 2 was not found." 
} 

/address/3應該返回:

{ 
    "detail": "Address 3 was not found." 
} 

回答

3

這聽起來像你想處理其中有一個404個狀態碼響應。修改例如從鏈接文件:

from rest_framework.views import exception_handler 

def custom_exception_handler(exc, context): 
    response = exception_handler(exc, context) 

    if response.data['status_code'] == 404: 
     try: 
      response.data['detail'] = "{name} {id} was not found.".format(
       name=context['view'].verbose_name, 
       id=context['kwargs']['id'] # this may need tweaking 
      ) 
     except AttributeError: 
      pass 

    return response 

然後添加相應的verbose_name到您的視圖。

+0

謝謝你的回答。當我要求'/ person/2'時,我得到一個'404 Not Found'狀態碼**不是** 401。 – Demetris

+0

謝謝。但是,這是一個通用的'404'嗎?我正在尋找特定的每個視圖。我道歉,我沒有在我原來的問題中包含這個。我已經做了更新以反映這一點。 – Demetris

+0

@ ivan-semochkin好的建議。 @Demetris您可以將自定義消息添加爲視圖方法,然後調用'context ['view']。get_custom_message()'。 – nimasmi

相關問題