Skip to content

Commit

Permalink
Implement create ingredients feature
Browse files Browse the repository at this point in the history
  • Loading branch information
pavlo-myskov committed Nov 7, 2023
1 parent d4329be commit b5eaa07
Showing 1 changed file with 18 additions and 1 deletion.
19 changes: 18 additions & 1 deletion app/recipe/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,10 +27,14 @@ class Meta:
class RecipeSerializer(serializers.ModelSerializer):
"""Serializer for recipes"""
tags = TagSerializer(many=True, required=False)
ingredients = IngredientSerializer(many=True, required=False)

class Meta:
model = Recipe
fields = ['id', 'title', 'time_minutes', 'price', 'link', 'tags']
fields = [
'id', 'title', 'time_minutes', 'price', 'link', 'tags',
'ingredients'
]
read_only_fields = ['id']

def _get_or_create_tags(self, tags, recipe):
Expand All @@ -44,14 +48,27 @@ def _get_or_create_tags(self, tags, recipe):
)
recipe.tags.add(tag_obj)

def _get_or_create_ingredients(self, ingredients, recipe):
"""Handle getting or creating ingredients as needed."""
auth_user = self.context['request'].user

for ingredient in ingredients:
ingredient_obj, create = Ingredient.objects.get_or_create(
user=auth_user,
**ingredient
)
recipe.ingredients.add(ingredient_obj)

def create(self, validated_data):
"""Create a recipe."""
# remove tags from validated data, before creating recipe
# since the recipe model expects tags to be created separately
# and added as relationship to recipe
tags = validated_data.pop('tags', [])
ingredients = validated_data.pop('ingredients', [])
recipe = Recipe.objects.create(**validated_data)
self._get_or_create_tags(tags, recipe)
self._get_or_create_ingredients(ingredients, recipe)

return recipe

Expand Down

0 comments on commit b5eaa07

Please sign in to comment.