Stop Raising ValidationError on create() on Serializers

Mangabo Kolawole - Apr 9 '22 - - Dev Community

When working with Django and also learning it, I've used to read but also write similar code.

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ["username", "password", "email"]

    def create(self, validated_data):
        username = validated_data.get("username")

        if username:
            try:
                User.objects.get(username=username)
                raise ValidationError({"user": "This user already exists."})
            except ObjectDoesNotExist:
                pass
        return User.objects.create(**validated_data)
Enter fullscreen mode Exit fullscreen mode

What is actually wrong with the code?
Well, we are raising ValidationError on the create() method instead of doing the work of data validation in the validate() or the validate_field() methods. 🥶

What are the implications?🤔

First of all, we are violating DRF rules and writing bad code. The fact that there is literally a function we can surcharge to make this task and it's not used is a pretty bad pattern.

And secondly, performance issues. The validation of the data comes actually before the creation, updating, and deletion of data.
Writing data validation on the validate() or the validate_field() methods can make CRUD methods much faster.🚀

Article posted using bloggu.io. Try it for free.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .