DEV Community

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

Posted on β€’ Originally published at Medium

9 1

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.

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

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

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay