The code:
class OTP(AppModel): phone_regex = RegexValidator(regex=r'^[6789]\d{9}$', message="phone no. is invalid.") phone_number = models.CharField(validators=[phone_regex], max_length=10, unique=True) code = models.CharField(max_length=255) def __str__(self): return str(self.phone_number) + ": "+str(self.code) class OTPSerializer(serializers.ModelSerializer): code = serializers.CharField(max_length=None, required=False) class Meta: model = OTP fields = ('id', 'code', 'phone_number') read_only_fields=('id', 'code') @transaction.atomic def create(self, validated_data): phone_number = validated_data.pop("phone_number") otp, created = OTP.objects.update_or_create( phone_number=phone_number, defaults={"code": generate_otp()}) return otp
I am trying to do update_or_create
inside the create
method of the django-rest-framework
's ModelSerializer
.
But, the field phone_number
inside the model OTP
must be unique
. Hence the unique=True
.
I was able to post a phone_number
and create the object. But, posting the same phone_number
again throws error otp with this phone number already exists
, instead of updating it if it already exists as I have overridden the create
method. Please help!