Best/correct practice for object-level validation errors? #1135
-
Is there a best/correct practice for implementing object-level validation and the ensuing validation errors? Django REST framework documentation suggests doing object-level validation in
So if I wanted to evaluate two fields and validate that only one of these fields is given data, I might implement my serializer something like this: from rest_framework_json_api import serializers
class ProductSerializer(serializers.ModelSerializer):
def validate(self, data):
if data.get("best_before_date") and data.get("expiry_date"):
raise serializers.ValidationError(
"Specify either a best before date or an expiry date."
)
return data However, using this serializer with django-rest-framework-json-api results in an error response that seems incorrect. {
"errors": [
{
"detail": "Specify either a best before date or an expiry date.",
"status": "400",
"source": {
"pointer": "/data/attributes/non_field_errors"
},
"code": "invalid"
}
]
} As far as I've understood, JSON:API error objects should have the source.pointer value as I thought about raising this as a bug report initially, but I'm not sure if this is actually a bug or if I'm just approaching this issue incorrectly. I also made a complete minimal example with unit tests of how I've implemented this. [1] https://www.django-rest-framework.org/api-guide/serializers/#object-level-validation |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
Thanks for your very detailed request. The way how you do validation on several fields is certainly correct. It seems you have found an issue with non field errors which DRF handles in a special manner but DJA is not aware of it. As a workaround you can use custom exceptions and set the pointer manually. Please file a bug where you outline your issue. Feel free to work on a PR if you desire. |
Beta Was this translation helpful? Give feedback.
Thanks for your very detailed request. The way how you do validation on several fields is certainly correct. It seems you have found an issue with non field errors which DRF handles in a special manner but DJA is not aware of it.
As a workaround you can use custom exceptions and set the pointer manually.
Please file a bug where you outline your issue. Feel free to work on a PR if you desire.