如何在django rest框架ModelSerializer中覆盖模型字段验证

时间:2021-05-15 19:18:36

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:

如果userprofile模型已经有一个移动号码XX44,并且如果我尝试使用带有json {'mobileNumber'的UserProfileSerializer序列化:'authKey':u'ggsdsagldaslhdkjashdjkashdjkahsdkjah'}我收到以下错误:

{'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.

如何停止执行mobileNumber的模型字段验证。我在序列化程序中尝试了validate和validate_mobileNumber方法,但它们仍在执行模型验证。

2 个解决方案

#1


2  

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

删除对表的移动数量的唯一约束,因此django序列化器将根据它进行验证。

or alternatively,

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

#2


0  

I understand you won't save the serializer data. So, you can set mobileNumber as a read_only field on UserProfileSerializer.

我知道你不会保存序列化数据。因此,您可以将MobileNumber设置为UserProfileSerializer上的read_only字段。

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

有关详细信息,请查看序列化程序字段文档:http://www.django-rest-framework.org/api-guide/fields/#core-arguments

#1


2  

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

删除对表的移动数量的唯一约束,因此django序列化器将根据它进行验证。

or alternatively,

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

#2


0  

I understand you won't save the serializer data. So, you can set mobileNumber as a read_only field on UserProfileSerializer.

我知道你不会保存序列化数据。因此,您可以将MobileNumber设置为UserProfileSerializer上的read_only字段。

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

有关详细信息,请查看序列化程序字段文档:http://www.django-rest-framework.org/api-guide/fields/#core-arguments