feat(recipe views): 增加菜谱原材料统计接口

增加菜谱原材料统计接口

Signed-off-by: Ching <loooching@gmail.com>
This commit is contained in:
Ching 2022-02-27 19:41:45 +08:00
parent bce303ceab
commit d16cfa0ca2
4 changed files with 42 additions and 0 deletions

View File

@ -141,6 +141,22 @@ class Recipe(models.Model):
}
return data
@classmethod
def sum_recipe_ingredients(cls, recipe_ids):
data = {}
for recipe_id in recipe_ids:
recipe = cls.objects.get(id=recipe_id)
recipe_ingredients = RecipeIngredient.objects.filter(recipe=recipe)
for ingredient in recipe_ingredients:
if not ingredient.ingredient.id in data:
data[ingredient.ingredient.id] = {
'name': ingredient.ingredient.name,
'quantity': 0,
'unit': ingredient.ingredient.unit,
}
data[ingredient.ingredient.id]['quantity'] += ingredient.quantity
return data
class DailyRecipe(models.Model):
recipes = models.ManyToManyField(Recipe)

View File

@ -58,6 +58,10 @@ class RecipeSerializer(serializers.ModelSerializer):
fields = ('recipe_ingredients', 'id', 'name', 'recipe_type', 'status', 'note', 'rate', 'difficulty')
class RecipeIngredientSummarySerializer(serializers.Serializer):
pass
class WeekRecipeSerializer(serializers.ModelSerializer):
class Meta:
model = recipe.models.DailyRecipe

View File

@ -17,6 +17,7 @@ recipe_nested_router.register(r'recipe-ingredient', views.RecipeIngredientAPI)
urlpatterns = [
url(r'^week-recipe/$', views.WeekRecipeListAPI.as_view()),
url(r'^daily-recipe/(?P<pk>\d+)$', views.DailyRecipeAPI.as_view(), name='dailyrecipe-detail'),
url(r'^ingredient-summary/$', views.RecipeIngredientSummaryAPI.as_view()),
path(r'', include(router.urls)),
path(r'', include(recipe_nested_router.urls)),
]

View File

@ -142,3 +142,24 @@ class RecipeIngredientAPI(viewsets.ModelViewSet):
recipe_id=kwargs['recipe_pk'], ingredient_id=request.data['ingredient'], quantity=request.data['quantity']
)
return Response(recipe_ingredient.serialize(), status=status.HTTP_201_CREATED, headers={})
# class RecipeIngredientSummaryAPI(viewsets.ViewSetMixin, rest_framework.generics.CreateAPIView):
class RecipeIngredientSummaryAPI(rest_framework.generics.CreateAPIView):
# authentication_classes = (authentication.TokenAuthentication,
# authentication.SessionAuthentication,
# authentication.BasicAuthentication)
# permission_classes = (permissions.IsAuthenticated,)
queryset = recipe.models.RecipeIngredient.objects.all()
serializer_class = recipe.serializers.RecipeIngredientSummarySerializer
def post(self, request, *args, **kwargs):
daily_recipe_ids = request.data.get('daily_recipes', [])
recipe_ids = request.data.get('recipes', [])
if daily_recipe_ids:
daily_recipes = recipe.models.DailyRecipe.objects.filter(id__in=daily_recipe_ids)
recipe_ids = [recipe.id for daily_recipe in daily_recipes for recipe in daily_recipe.recipes.all()]
data = recipe.models.Recipe.sum_recipe_ingredients(recipe_ids)
return Response(data, status=status.HTTP_200_OK, headers={})