10👍
DRF doesn’t validate UniqueConstraint
s the way it does unique_together
.
The reason for this is because unique constraints can be more complex than just "this collection of fields must have unique values". Consider the following:
UniqueConstraint(
fields=["author", "slug"],
condition=Q(status="published"),
name="author_slug_published_uniq",
)
This constraint only validates that the row is unique if the status is published
, i.e. there can be multiple rows with the same slug and author if they are all drafts. Because of this complexity, there isn’t a validator for this. However, for this simple case, you can add DRF’s UniqueTogether
validator manually:
class ClientSerializer(serializers.ModelSerializer):
class Meta:
fields = ["id", "name", "description", "company"]
validators = [
UniqueTogetherValidator(
queryset=Client..objects.all(),
fields=["name", "company"],
)
]
Source:stackexchange.com