Skip to content

Commit

Permalink
add code for creating ingredients [expect to pass]
Browse files Browse the repository at this point in the history
  • Loading branch information
mrcongliu committed Jan 18, 2024
1 parent 13ac2ff commit d8cab33
Showing 1 changed file with 15 additions and 1 deletion.
16 changes: 15 additions & 1 deletion app/recipe/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,10 +31,12 @@ 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 @@ -48,11 +50,23 @@ 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, created = Ingredient.objects.get_or_create(
user=auth_user,
**ingredient,
)
recipe.ingredients.add(ingredient_obj)

def create(self, validated_data):
"""Create a 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 d8cab33

Please sign in to comment.