Advertisement
AlRia

Untitled

Nov 12th, 2023
37
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.80 KB | None | 0 0
  1. class RecipeViewSet(viewsets.ModelViewSet):
  2. queryset = Recipe.objects.prefetch_related(
  3. 'author', 'tags', 'ingredients').all()
  4. serializer_class = RecipeSerializer
  5. permission_classes = (IsCreatorOrReadOnly,)
  6. filter_backends = (DjangoFilterBackend,)
  7. filterset_class = RecipeFilter
  8.  
  9. def create_delete_recipe(self, request, pk, sent_serializer, model):
  10. recipe = get_object_or_404(Recipe, pk=pk)
  11. if request.method == 'POST':
  12. serializer = sent_serializer(
  13. data={'user': request.user.id, 'recipe': recipe.id}
  14. )
  15. serializer.is_valid(raise_exception=True)
  16. serializer.save()
  17. additional_recipe_serializer = AdditionalRecipeSerializer(recipe)
  18. return Response(
  19. additional_recipe_serializer.data,
  20. status=status.HTTP_201_CREATED,
  21. )
  22. specific_recipe = get_object_or_404(
  23. model, user=request.user, recipe=recipe
  24. )
  25. specific_recipe.delete()
  26. return Response(status=status.HTTP_204_NO_CONTENT)
  27.  
  28. @action(
  29. detail=True,
  30. methods=['post', 'delete'],
  31. url_path='favorite',
  32. permission_classes=(IsAuthenticated,)
  33. )
  34. def favorite(self, request, pk):
  35. return self.create_delete_recipe(
  36. request, pk, FavoriteSerializer, Favorite)
  37.  
  38. @action(
  39. detail=True,
  40. methods=['post', 'delete'],
  41. url_path='shopping_cart',
  42. permission_classes=(IsAuthenticated,)
  43. )
  44. def shopping_cart(self, request, pk):
  45. return self.create_delete_recipe(
  46. request, pk, ShoppingListSerializer, ShoppingList)
  47.  
  48. def create_shopping_list(self, ingredients):
  49. shopping_list = ''
  50. for ingredient in ingredients:
  51. shopping_list += (
  52. f"{ingredient['ingredient__name']}: "
  53. f"{ingredient['sum']}"
  54. f"({ingredient['ingredient__measurement_unit']})\n"
  55. )
  56. return shopping_list
  57.  
  58. @action(
  59. detail=False,
  60. methods=['get'],
  61. permission_classes=(IsAuthenticated,),
  62. url_path='download_shopping_cart',
  63. )
  64. def download_shopping_list(self, request):
  65. ingredients = RecipeIngredient.objects.filter(
  66. recipe__shopping_list__user=request.user
  67. ).values(
  68. 'ingredient__name',
  69. 'ingredient__measurement_unit'
  70. ).annotate(sum=Sum('amount'))
  71. shopping_list = self.create_shopping_list(ingredients)
  72. response = HttpResponse(shopping_list, content_type='text/plain')
  73. return response
  74.  
  75. def get_serializer_class(self):
  76. if self.request.method == 'GET':
  77. return RecipeSafeSerializer
  78. return RecipeSerializer
  79.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement