How to override model field validation in django rest ModelSerializer

I have the following model:

class UserProfile(models.Model): mobileNumber = models.BigIntegerField(primary_key=True) authKey = models.CharField(max_length=300,null=False,blank=False) creationDateTime = models.DateTimeField(auto_now_add=True) lastUpdateDateTime = models.DateTimeField(auto_now=True) 

Serializer:

 class UserProfileSerializer(serializers.ModelSerializer): class Meta: model = UserProfile fields = ('mobileNumber','authKey') 

If the userprofile model already has mobilenumber XX44, and if I try to serialize using UserProfileSerializer with json {'mobileNumber': XX44, 'authKey': u'ggsdsagldaslhdkjashdjkashdjkahsdkjah '}, I get the following error:

 {'mobileNumber': [u'User profile with this MobileNumber already exists.']} 

since model checks are performed for the serializer field.

How to stop model field validation for mobileNumber. I tried to validate and validate_mobileNumber methods in the serializer, but they still do model validation.

+9
source share
3 answers

remove the unique restriction for the mobile table number, so django serializer will check accordingly.

or alternatively,

  serializer=UserProfileSerializer(data=request.DATA,partial=True) 
+2
source

As far as I understand, you will not save serializer data. That way you can set mobileNumber as the read_only field to UserProfileSerializer .

Check the serializer fields documentation for more information: http://www.django-rest-framework.org/api-guide/fields/#core-arguments

0
source

Overriding the model field in the serializer and specifying required=False, allow_blank=True, allow_null=True :

 class SomeModel(models.Model): some_model_field_which_is_required = models.ForeignKey(...) some_other_required_field = models.CharField(...) class SomeModelSerializer(serializers.ModelSerializer): some_model_field_which_is_required = SomeNestedSerializer( many=True, required=False, allow_blank=True ) some_other_required_field = serializers.CharField(required=False, allow_blank=True) def validate(self, *args, **kwargs): print('should get here') def validate_some_other_required_field(self, *args, **kwargs): print('should also get here') class Meta: model = SomeModel 
0
source

All Articles