Situation
While working with validation in the Django REST Framework's ModelSerializer, I have noticed that the Meta.model fields are always validated, even when it does not necessarily make sense to do so. Take the following example for a User model's serialization:
- I have an endpoint that creates a user. As such, there is a
passwordfield and aconfirm_passwordfield. If the two fields do not match, the user cannot be created. Likewise, if the requestedusernamealready exists, the user cannot be created. - The user POSTs improper values for each of the fields mentioned above
- An implementation of
validatehas been made in the serializer (see below), catching the non-matchingpasswordandconfirm_passwordfields
Implementation of validate:
def validate(self, data):
if data['password'] != data.pop('confirm_password'):
raise serializers.ValidationError("Passwords do not match")
return data
Problem
Even when the ValidationError is raised by validate, the ModelSerializer still queries the database to check to see if the username is already in use. This is evident in the error-list that gets returned from the endpoint; both the model and non-field errors are present.
Consequently, I would like to know how to prevent model validation until after non-field validation has finished, saving me a call to my database.
Attempt at solution
I have been trying to go through the DRF's source to figure out where this is happening, but I have been unsuccessful in locating what I need to override in order to get this to work.
