Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to catch sql error in Django Rest Framework serializer?

I've got a Django Rest Framework endpoint to which an external party sends data in a fairly high volume. Because it was running about 200 inserts per second I checked the queries it was making. I found that it actually first did a SELECT query to check whether there was a duplicate id. Since I didn't think there would be any (or at least not many) duplicate keys I wanted to disable that check. So I added this line to my Serializer:

id = serializers.UUIDField(validators=[])  # Disable the validators for the id, which improves performance (rps) by over 200%

And as you can see in the comment, it greatly enhances the performance. However, one disadvantage of it is that it gives a 500 error if a duplicate key is in fact posted, saying

duplicate key value violates unique constraint

How would I be able to catch this Database error and returning a neat response instead of throwing this 500 error?

like image 341
kramer65 Avatar asked Dec 10 '25 20:12

kramer65


1 Answers

One way to do it would be to override the serializer's create method to catch the error.

from django.db import IntegrityError
from django.core.exceptions import ValidationError

from rest_framework import serializers

class MySerializer(serializers.ModelSerializer):

    [ ... ]

    def create(self, validated_data):
        try:
            return super().create(validated_data)
        except IntegrityError as e:
            raise serializers.ValidationError(str(e))

You have to override the serializer's update as well if you allow PUT on the object.

There might be better to place the hook, depending on your use case. It have to be somewhere on the serializer and the try-catch has to be around where the objects save() method is called. For you, it might work to override the serializer's save() method with roughly the same code as above.

like image 58
Ted Klein Bergman Avatar answered Dec 13 '25 08:12

Ted Klein Bergman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!