mercredi 30 novembre 2022

need a better way to validate fields in request body django depending on a specific field value

The requirement is to verify body fields in an api request depending on another field.

Like: the request data has a field:

action

If actions is deactivate then no other field should be present in the body data however if the action is anything else we want to allow updating other fields as well such as name.

currently we have a validation where we are going through the dictionary keys and comparing like below:

expected_keys = ['client_updated', 'updated_by', 'actions']
if key not in expected_keys:
    raise ValidationError("Deactivation action does not allow {} to be updated".format(key))

Just wanted to know if there is a better way to handle via django or django rest framework, with somewhat less harcoding.

Aucun commentaire:

Enregistrer un commentaire