Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)

like image 653
Safari Avatar asked Sep 01 '17 11:09

Safari


2 Answers

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 []
like image 70
arjunattam Avatar answered Nov 20 '22 00:11

arjunattam


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

Although not exactly the same, the steps are explained here

like image 36
Linovia Avatar answered Nov 19 '22 23:11

Linovia