Pretty sure you need to sort these operations by the primary key of the model, or some other deterministic ordering. Otherwise you could deadlock between two transactions each transferring a model in opposite directions, since this code is locking the parent records in a different order.