Представь что ты программист Django. У меня есть методы отправки подтверждения юзера по номеру телефона:

class SendOrResendSMSAPIView(GenericAPIView):
    """
    Check if submitted phone number is a valid phone number and send OTP.
    """
    serializer_class = PhoneNumberSerializer

    def post(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)

        if serializer.is_valid():
            # Send OTP
            phone_number = str(serializer.validated_data['phone_number'])

            user = CustomUser.objects.filter(
                phone__phone_number=phone_number).first()

            sms_verification = PhoneNumber.objects.filter(
                user=user, is_verified=False).first()

            sms_verification.send_confirmation()

            return Response(status=status.HTTP_200_OK)

        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
        
и метод отправки подтверждения юзера по email:

from dj_rest_auth.registration.views import ResendEmailVerificationView

Нужно переписать логику обновления у юзера email, phone_number, first_name и last_name. У меня для этого есть модель юзера: 

class CustomUser(AbstractUser):
    APPLICANT = "Applicant"
    EMPLOYER = "Employer"
    ROLE_CHOICES = (
        (APPLICANT, "Applicant"),
        (EMPLOYER, "Employer"),
    )
    username = models.CharField(max_length=255, unique=True, blank=True, null=True)
    email = models.EmailField(_("email address"), unique=False, max_length=254, blank=True,null=True)
    role = models.CharField(max_length=50, choices=ROLE_CHOICES)
    avatar = models.ImageField(_("avatar"), upload_to="avatars/", null=True, blank=True)
    is_staff = models.BooleanField(default=False)
    is_active = models.BooleanField(default=True)
    created_date = models.DateTimeField(auto_now_add=True)
    updated_date = models.DateTimeField(auto_now=True)
    blocked_until = models.DateTimeField(null=True, blank=True)
    USERNAME_FIELD = "username"
    REQUIRED_FIELDS = []

    objects = UserManager()

    def __str__(self):
        return self.email

    @property
    def fullname(self):
        return f"{self.first_name} {self.last_name}"

модель телефона:

class PhoneNumber(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    user = models.OneToOneField(CustomUser, related_name='phone', on_delete=models.CASCADE)
    phone_number = PhoneNumberField(unique=True)
    security_code = models.CharField(max_length=120)
    is_verified = models.BooleanField(default=False)
    sent = models.DateTimeField(null=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        ordering = ('-created_at', )

    def __str__(self):
        return self.phone_number.as_e164

    def generate_security_code(self):
        """
        Returns a unique random `security_code` for given `TOKEN_LENGTH` in the settings.
        Default token length = 6
        """
        token_length = getattr(base, "TOKEN_LENGTH", 6)
        return get_random_string(token_length, allowed_chars="0123456789")

    def is_security_code_expired(self):
        expiration_date = self.sent + datetime.timedelta(
            minutes=base.TOKEN_EXPIRE_MINUTES
        )
        return expiration_date <= timezone.now()

    def send_confirmation(self):
        twilio_account_sid = base.TWILIO_ACCOUNT_SID
        twilio_auth_token = base.TWILIO_AUTH_TOKEN
        twilio_phone_number = base.TWILIO_PHONE_NUMBER

        self.security_code = self.generate_security_code()

        # print(
        #     f'Sending security code {self.security_code} to phone {self.phone_number}')

        if all(
            [
                twilio_account_sid,
                twilio_auth_token,
                twilio_phone_number
            ]
        ):
            try:
                twilio_client = Client(
                    twilio_account_sid, twilio_auth_token
                )
                twilio_client.messages.create(
                    body=f'Your activation code is {self.security_code}',
                    to=str(self.phone_number),
                    from_=twilio_phone_number,
                )
                self.sent = timezone.now()
                self.save()
                return True
            except TwilioRestException as e:
                print(e)
        else:
            print("Twilio credentials are not set")

    def check_verification(self, security_code):
        if (
            not self.is_security_code_expired() and
            security_code == self.security_code and
            self.is_verified == False
        ):
            self.is_verified = True
            self.save()
        else:
            raise NotAcceptable(
                _("Your security code is wrong, expired or this phone is verified before."))

        return self.is_verified


сериализатор обновления номера телефона:

class PhoneNumberUpdateSerializer(serializers.ModelSerializer):
    class Meta:
        model = PhoneNumber
        fields = ('phone_number',)

сериализатор обновления юзера:

class UserUpdateSerializer(serializers.ModelSerializer):
    phone = PhoneNumberUpdateSerializer()

    class Meta:
        model = CustomUser
        fields = ('email', 'first_name', 'last_name', 'phone')

    def update(self, instance, validated_data):
        if 'email' in validated_data:
            instance.email = validated_data['email']
        if 'first_name' in validated_data:
            instance.first_name = validated_data['first_name']
        if 'last_name' in validated_data:
            instance.last_name = validated_data['last_name']
        if 'phone' in validated_data:
            phone_data = validated_data.pop('phone')
            phone = instance.phone
            if not phone:
                phone = PhoneNumber(user=instance)
            for key, value in phone_data.items():
                setattr(phone, key, value)
            phone.save()
        instance.save()
        return instance

и представление обновления юзера, которое вызывает ошибку: django.db.transaction.TransactionManagementError: An error occurred in the current transaction. You can't execute queries until the end of the 'atomic' block.

представление:

class UserUpdateApi(generics.UpdateAPIView):
    serializer_class = UserUpdateSerializer

    def get_object(self):
        return self.request.user

    def _send_sms(self, request, *args, **kwargs):
        res = SendOrResendSMSAPIView.as_view()(request._request, *args, **kwargs)
        return res.status_code == 200

    def _send_email_verification(self, request, *args, **kwargs):
        res = ResendEmailVerificationView.as_view()(request._request, *args, **kwargs)
        return res.status_code == 200

    def _send_verification_messages(self, request, email, phone, *args, **kwargs):
        response_data = {}

        if phone:
            phone_data = request.data.get('phone', {})
            phone_serializer = PhoneNumberUpdateSerializer(phone, data=phone_data, partial=True)
            if phone_serializer.is_valid(raise_exception=True):
                phone_serializer.save()
                response_data['phone'] = phone_serializer.data

        if email:
            if self._send_email_verification(request, *args, **kwargs):
                response_data['email'] = {'detail': _('Verification e-mail sent.')}

        if phone and self._send_sms(request, *args, **kwargs):
            message = _('Verification e-mail and SMS sent.')
        elif not phone and email:
            message = _('Verification e-mail sent.')
        elif phone and not email:
            message = _('Verification SMS sent.')
            if self._send_sms(request, *args, **kwargs):
                response_data['detail'] = message
        elif not phone and not email:
            message = _('No verification method specified.')
        else:
            message = _('Verification e-mail and SMS sent.')

        response_data['detail'] = message

        return response_data

    def update(self, request, *args, **kwargs):
        response_data = {}
        user = self.get_object()

        phone = user.phone if hasattr(user, 'phone') else None
        email = request.data.get('email', None)

        serializer = self.get_serializer(user, data=request.data, partial=True)
        serializer.is_valid(raise_exception=True)

        self.perform_update(serializer)

        response_data.update(self._send_verification_messages(request, email, phone, *args, **kwargs))

        return Response({**serializer.data, **response_data}, status=status.HTTP_200_OK)


Нужно переписать код таким образом, чтоб любые поля юзера обновлялись без ошибок и отправлялись в зависимости от обновляемого поля подтверждения по смс либо email.