Safari
Safari

Reputation: 11965

Django Rest Framework model serializer with out unique together validation

I have a model with some fields and a unique together:

....
class Meta(object):
    unique_together = ('device_identifier', 'device_platform',)

Obviously, in this way, about Django rest framework serializer, I obtain an error when I try to make a PUT with the same device_identifier and device_platform (if already exist an entry with this data).

{
  "non_field_errors": [
    "The fields device_identifier, device_platform must make a unique set."
  ]
}

Is possible to disable this validation in my model serializer? Because I need to manage this situation during save model step (for me, in serializer validation this is not an error)

Upvotes: 24

Views: 9644

Answers (2)

arjunattam
arjunattam

Reputation: 2819

Django REST framework applies the UniqueTogetherValidator on the serializer. You can remove this by override the validators field in the serializer definition.

class ExampleSerializer(serializers.ModelSerializer):
    class Meta:
        validators = []

Note that this also removes the other unique-check validators that are applied on the model, which might not be the best idea. To avoid that, just override the get_unique_together_validators method on the serializer, to ensure only unique-together check is removed.

class ExampleSerializer(serializers.ModelSerializer):
    def get_unique_together_validators(self):
        """Overriding method to disable unique together checks"""
        return []

Upvotes: 42

Linovia
Linovia

Reputation: 20996

You need to remove the validator from the serializer's list.

Although not exactly the same, the steps are explained here

Upvotes: 1

Related Questions