-
Notifications
You must be signed in to change notification settings - Fork 300
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 Serializer.validate()[1].
To do any other validation that requires access to multiple fields, add a method called
.validate()to yourSerializersubclass. This method takes a single argument, which is a dictionary of field values. It should raise aserializers.ValidationErrorif necessary, or just return the validated values.
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 "/data/attributes/<attribute>" when an error is caused by a specific attribute, and "/data" in other cases[2].
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
[2] https://jsonapi.org/format/#error-objects
Beta Was this translation helpful? Give feedback.
All reactions
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.
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.