Serializer: object-level validation does not provide all fields in partial update

183 views
Skip to first unread message

Ling-Xiao Yang

unread,
Dec 16, 2014, 11:16:28 AM12/16/14
to django-res...@googlegroups.com
Hi,

I'm implementing an object-level validation that constraints the combination of values of two fields, by providing the `validate(self, data)` method to the serializer class. The problem I encounter is, the parameter `data` contains only the fields provided by the PATCH request during partial update. The client may request to modify one of the two fields, but both the values of two fields are needed to validate the change.

It's doable to check `self.instance.field_name` when `partial=True` and the field is not in `data`, but it complicates the code a bit. Is there any cleaner way to achieve the object-level validation?

Thanks,
Ling-Xiao

Tom Christie

unread,
Dec 17, 2014, 9:21:54 AM12/17/14
to django-res...@googlegroups.com
That's correct. For `required=False` fields, or for partial updates, the field won't be present in validation data if it's not included in the request.
If you *do* need to inspect any of the instance attributes you can do so using `self.instance`, as you note. Agree that it's not the most graceful, but it's probably better than us trying to automatically determine the correct attribute to lookup, which would be...

* Liable to be incorrect under various custom cases, or nested lookups.
* Obfuscate if the user had supplied the value or not.
Reply all
Reply to author
Forward
0 new messages