Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class RecipeViewSet(viewsets.ModelViewSet):
- queryset = Recipe.objects.prefetch_related(
- 'author', 'tags', 'ingredients').all()
- serializer_class = RecipeSerializer
- permission_classes = (IsCreatorOrReadOnly,)
- filter_backends = (DjangoFilterBackend,)
- filterset_class = RecipeFilter
- def create_delete_recipe(self, request, pk, sent_serializer, model):
- recipe = get_object_or_404(Recipe, pk=pk)
- if request.method == 'POST':
- serializer = sent_serializer(
- data={'user': request.user.id, 'recipe': recipe.id}
- )
- serializer.is_valid(raise_exception=True)
- serializer.save()
- additional_recipe_serializer = AdditionalRecipeSerializer(recipe)
- return Response(
- additional_recipe_serializer.data,
- status=status.HTTP_201_CREATED,
- )
- specific_recipe = get_object_or_404(
- model, user=request.user, recipe=recipe
- )
- specific_recipe.delete()
- return Response(status=status.HTTP_204_NO_CONTENT)
- @action(
- detail=True,
- methods=['post', 'delete'],
- url_path='favorite',
- permission_classes=(IsAuthenticated,)
- )
- def favorite(self, request, pk):
- return self.create_delete_recipe(
- request, pk, FavoriteSerializer, Favorite)
- @action(
- detail=True,
- methods=['post', 'delete'],
- url_path='shopping_cart',
- permission_classes=(IsAuthenticated,)
- )
- def shopping_cart(self, request, pk):
- return self.create_delete_recipe(
- request, pk, ShoppingListSerializer, ShoppingList)
- def create_shopping_list(self, ingredients):
- shopping_list = ''
- for ingredient in ingredients:
- shopping_list += (
- f"{ingredient['ingredient__name']}: "
- f"{ingredient['sum']}"
- f"({ingredient['ingredient__measurement_unit']})\n"
- )
- return shopping_list
- @action(
- detail=False,
- methods=['get'],
- permission_classes=(IsAuthenticated,),
- url_path='download_shopping_cart',
- )
- def download_shopping_list(self, request):
- ingredients = RecipeIngredient.objects.filter(
- recipe__shopping_list__user=request.user
- ).values(
- 'ingredient__name',
- 'ingredient__measurement_unit'
- ).annotate(sum=Sum('amount'))
- shopping_list = self.create_shopping_list(ingredients)
- response = HttpResponse(shopping_list, content_type='text/plain')
- return response
- def get_serializer_class(self):
- if self.request.method == 'GET':
- return RecipeSafeSerializer
- return RecipeSerializer
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement