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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With