Place spaghetti squash in a covered dish and add 1/4 inch of water. Microwave for 10 to 12 minutes. Scrape insides of squash with a fork and transfer to a small bowl.
Heat margarine in a medium skillet over medium heat while spaghetti squash is cooking and cook onion, red pepper flakes, garlic powder, salt, and pepper until the onion is browned, 5 to 10 minutes.
Preheat the oven to 375 degrees F (190 degrees C). Grease a baking dish with nonstick cooking spray.
Mix spaghetti squash, onion mixture, sour cream, and 1/2 of the Cheddar cheese together. Transfer to the prepared baking dish and top with remaining Cheddar cheese.
Bake in the preheated oven for 20 to 25 minutes. Turn on broiler for the last 2 to 3 minutes and broil until gratin is golden brown on top.