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
password
field and a confirm_password
field. If the two fields do not match, the user cannot be created. Likewise, if the requested username
already exists, the user cannot be created.
- The user POSTs improper values for each of the fields mentioned above
- An implementation of
validate
has been made in the serializer (see below), catching the non-matching password
and confirm_password
fields
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.
question from:
https://stackoverflow.com/questions/27591574/order-of-serializer-validation-in-django-rest-framework 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…