DEV Community

Cover image for Stop Raising ValidationError on create() on Serializers
Mangabo Kolawole
Mangabo Kolawole

Posted on • Originally published at Medium

Stop Raising ValidationError on create() on Serializers

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.

Top comments (4)

Collapse
 
fayomihorace profile image
Horace FAYOMI

Indeed we should use and leverage the right tool at the Right place.
Thanks for sharing.

Collapse
 
koladev profile image
Mangabo Kolawole

Definitely πŸš€πŸš€

Collapse
 
furtleo profile image
Leonardo Furtado

Nice post

Collapse
 
sm0ke profile image
Sm0ke

Niceeee