Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to override model field validation in django rest framework 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 userprofile model already has a mobilenumber XX44 and if I try to serialize using UserProfileSerializer with json {'mobileNumber': XX44, 'authKey': u'ggsdsagldaslhdkjashdjkashdjkahsdkjah'} I'm getting the following error:

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

because model validations are being run for the serializer field.

How can I stop execution of model field validation for mobileNumber. I have tried validate and validate_mobileNumber methods in serializer but they still are executing the model validations.

like image 292
Rahul Attuluri Avatar asked Mar 25 '14 12:03

Rahul Attuluri


People also ask

What is the difference between ModelSerializer and HyperlinkedModelSerializer?

The HyperlinkedModelSerializer class is similar to the ModelSerializer class except that it uses hyperlinks to represent relationships, rather than primary keys. By default the serializer will include a url field instead of a primary key field.

How do you pass extra context data to Serializers in Django REST framework?

In function based views we can pass extra context to serializer with "context" parameter with a dictionary. To access the extra context data inside the serializer we can simply access it with "self. context". From example, to get "exclude_email_list" we just used code 'exclude_email_list = self.

How does Django validate data in serializer?

Validation in Django REST framework serializers is handled a little differently to how validation works in Django's ModelForm class. With ModelForm the validation is performed partially on the form, and partially on the model instance. With REST framework the validation is performed entirely on the serializer class.

What is Validated_data in Django rest?

validated_data is an OrderedDict and you can see it only after is_valid() and is_valid() == True.


1 Answers

remove unique constraint on mobile number of table,so django serializer will validate according to that .

or alternatively,

   serializer=UserProfileSerializer(data=request.DATA,partial=True)
like image 179
user3635290 Avatar answered Sep 18 '22 07:09

user3635290