use CASA applycal
It would be good to use CASA applycal for applying/unapplying gains. It would be both faster and should have better results because of proper interpolation between solutions.
Current limitation is that applycal does not unapply, so solutions need to be pre-inverted. Additionally, it may not be possible to operate on the MODEL_DATA column, which is required.