- Notifications
You must be signed in to change notification settings - Fork302
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: fromrest_framework_json_apiimportserializersclassProductSerializer(serializers.ModelSerializer):defvalidate(self,data):ifdata.get("best_before_date")anddata.get("expiry_date"):raiseserializers.ValidationError("Specify either a best before date or an expiry date." )returndata 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 madea 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 |
BetaWas 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 usecustom 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 usecustom 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. |
BetaWas this translation helpful?Give feedback.