2017-06-26 32 views
0

默認驗證錯誤消息定製驗證錯誤消息是密鑰和消息的列表。將這種格式自定義爲文本格式的最佳方式是什麼?例如。使用由DRF給出Django的REST框架

這是默認格式。

{ 
"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

您可以覆蓋串行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