"""Create an independent variation from one owned recipe.""" from django.db import transaction from recipes.models import (Recipe, RecipeIngredient, RecipeIngredientSubstitution, RecipeSubrecipe) @transaction.atomic def create_variation(user, parent, title=None): if parent.owner_id != user.pk: raise ValueError('Recipe not found.') variation = Recipe.objects.create( owner=user, parent=parent, title=title or f'{parent.title[:160]} variation', description=parent.description, instructions_markdown=parent.instructions_markdown, notes_markdown=parent.notes_markdown, preparation_minutes=parent.preparation_minutes, cooking_minutes=parent.cooking_minutes, default_servings=parent.default_servings, yield_amount=parent.yield_amount, yield_unit=parent.yield_unit, category=parent.category, tags=list(parent.tags), status=Recipe.Status.DRAFT) for item in parent.ingredients.select_related('inventory_product', 'nutrition_product').prefetch_related('substitutions'): copied = RecipeIngredient.objects.create( recipe=variation, name=item.name, quantity=item.quantity, unit=item.unit, amount_per_unit=item.amount_per_unit, amount_per_unit_unit=item.amount_per_unit_unit, display_order=item.display_order, inventory_product=item.inventory_product, nutrition_product=item.nutrition_product, preparation_note=item.preparation_note, is_optional=item.is_optional) RecipeIngredientSubstitution.objects.bulk_create([ RecipeIngredientSubstitution( ingredient=copied, name=alternative.name, quantity=alternative.quantity, unit=alternative.unit, amount_per_unit=alternative.amount_per_unit, amount_per_unit_unit=alternative.amount_per_unit_unit, product=alternative.product, display_order=alternative.display_order) for alternative in item.substitutions.all()]) RecipeSubrecipe.objects.bulk_create([ RecipeSubrecipe(recipe=variation, component=item.component, quantity=item.quantity, unit=item.unit, display_order=item.display_order, note=item.note) for item in parent.subrecipes.all()]) return variation