2017-06-26 14 views
0

DRFによって指定されるデフォルトの検証エラーメッセージは、キーとメッセージのリストです。この形式をテキスト形式にカスタマイズする最も良い方法は何でしょうか。例えば。Django Rest Frameworkを使用したカスタム検証エラーメッセージ

これがデフォルトの形式です。

{ 
"message": { 
    "phone": [ 
     "customer with this phone already exists." 
    ], 
    "email": [ 
     "customer with this email already exists." 
    ], 
    "tenant_id": [ 
     "customer with this tenant id already exists." 
    ] 
}, 
"success": false, 
"error": 1 
} 

これは私が欲しいものです。

{ 
"message": "customer with this phone already exists, customer with this 
email already exists, customer with this tenant id already exists" 
"success": false, 
"error": 1 
} 

答えて

0

1つの一般メッセージを提供する代わりに、個々のフィールドの検証メッセージを表示するのが一般的です。したがって、DRFのデフォルト動作はこの規約に従います。

目的を達成するには、シリアライザhttp://www.django-rest-framework.org/api-guide/serializers/#object-level-validationのオブジェクトレベルの検証を作成し、フィールド検証のデフォルト動作を防止する必要があります。

0

あなたはシリアライザvalidate()メソッドをオーバーライドして、カスタム検証を上げることができ、

def validate(self, data): 
    #validations here.. 
    response = { 
        "message": "customer with this phone already 
           exists, customer with this 
           email already exists, customer with 
           this tenant id already exists" 
        "success": false, 
        "error": 1 
       } 
    try: 
     Customer.objects.get(phone=data['phone'], email=data['email'], 
          tenant_id=data['tenant_id']) 
     raise serializers.ValidationError(response["message"]) 
     #or you could return a json response. 
     #return Response(response) 
    except: 
     return data 
関連する問題