I have a Django model defined with a unique_together relationship defined between name and address, shown below:
class Person(models.Model):
name = models.CharField(max_length=255, default='', null=False)
address = models.CharField(max_length=255, default='', null=False)
class Meta:
unique_together = ('name', 'address')
I also have a Django REST Framework serializer with a UniqueTogetherValidator describing the same constraint as defined in the model, shown below:
class PersonSerializer(serializers.ModelSerializer):
class Meta:
model = Person
fields = (
'name', 'address',
)
validators = [
UniqueTogetherValidator(
queryset=Branch.objects.all(),
fields=['name', 'address']
)
]
While testing this constraint, I noticed that the exact same behavior is exhibited whether or not I have the UniqueTogetherValidator added to the PersonSerializer. The same error message is returned whether or not I include this (due to the unique_together defined on the model).
My question is: what is the reason for explicitly declaring validators on the serializer if the behavior is performed behind the scenes? I did notice you can change the error message, but this seems like quite a bit of boilerplate for solely manipulating an error message for violating a unique_together constraint. Is there a broader reason for utilizing these validator classes that I'm missing?