DRF - Checking for a concrete unique constraint violation when creating and/or validating an object
Solution 1:
Every type of validation should be done in DRF validation methods i.e. validate
and is_valid
. For your case, you should check in your validate method if any object already exists against provided data like this
def is_valid(self, raise_exception=True):
data = self.initial_data
if TestModel.objects.filter(fieldA=data.get('fieldA'), fieldB=data.get('fieldB').exists():
raise serializers.ValidationError("Object already exist with {fieldA} and {fieldB}".format(**data)
return super().is_valid(raise_exception)