def update_menu(request, pk): """ 修改指定菜单 --- serializer: menu.serializers.MenuSerializer omit_serializer: false responseMessages: - code: 400 message: Bad Request - code: 404 message: Not Found - code: 401 message: Not authenticated """ try: menu = Menu.objects.get(pk=pk) except Menu.DoesNotExist: return Response('menu type not found', status=status.HTTP_404_NOT_FOUND) serializer = MenuSerializer(menu, data=request.DATA, partial=True) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_202_ACCEPTED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def put(self, request, pk): menu = self.get_object(pk) serializer = MenuSerializer(menu, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def post(self, request): data = request.data serializer = MenuSerializer(data=data) if serializer.is_valid(): serializer.save() # print(serializer.data['id']) return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def post(self, request, format=None): data = request.data.copy() data['user_id'] = request.user.id serializer = MenuSerializer(data=data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) #print('SE', serializer.errors) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def test_validation(self): self.serializer_data['name'] = 'Nazwa update' serializer = MenuSerializer(data=self.serializer_data) serializer.is_valid() new_menu = serializer.save() new_menu.refresh_from_db() self.assertEqual(new_menu.name, 'Nazwa update')
def get(self, request, format=None): user = User(pk=request.user.id) menu_list = Menu.objects.filter( user=user, end_date__gte=datetime.now()).order_by('start_date')[:30] serializer = MenuSerializer(menu_list, many=True) return Response(serializer.data)
def setUp(self): self.user = User.objects.create_user(username='******', email='*****@*****.**', password='******') self.menu = Menu.objects.create(name='Test Menu 1', description='Test menu description 1', author=self.user) self.dish_meat = Dish.objects.create( name='Test Meat Dish 1', description='Test meat description 1', price='10.50', prep_time=60, is_vegetarian=False, author=self.user) self.menu.dish.add(self.dish_meat) self.serializer_input = Menu.objects.all() self.serializer = MenuSerializer(data=self.serializer_input, many=True) self.serializer.is_valid()
def test_menu_list_viwe(self): factory = APIRequestFactory() view = MenuListApiView.as_view() menu_objects = Menu.objects.all() serializer = MenuSerializer(menu_objects, many=True) url = reverse('menu:api-menu-list') request = factory.get(url) response = view(request) response_result = dict(response.data.items()).get('results') self.assertEqual(response.status_code, 200) self.assertNotEqual(response_result, serializer.data) # Empty List, Menu without dish
def menu_list(request, format=None): if request.method == 'GET': menu = Menu.objects.all() serializer = MenuSerializer(menu, many=True) return Response(serializer.data) elif request.method == 'POST': serializer = MenuSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def create_menu(request): """ 创建菜单 --- serializer: menu.serializers.MenuSerializer omit_serializer: false responseMessages: - code: 201 message: Created - code: 400 message: Bad Request - code: 401 message: Not authenticated """ data = request.DATA.copy() serializer = MenuSerializer(data=data) if serializer.is_valid(): menu = serializer.save() menu.restaurant = request.current_restaurant menu.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
class RestaurantSerializer(serializers.ModelSerializer): menu = MenuSerializer(required=False, many=True, read_only=True) type = RestaurantTypeSerializer(read_only=True) class Meta: model = Restaurant fields = [ 'id', 'name', 'address', 'type', 'image', 'menu', ]
class MenuSerializerTests(TestCase): def setUp(self): self.user = User.objects.create_user(username='******', email='*****@*****.**', password='******') self.menu = Menu.objects.create(name='Test Menu 1', description='Test menu description 1', author=self.user) self.dish_meat = Dish.objects.create( name='Test Meat Dish 1', description='Test meat description 1', price='10.50', prep_time=60, is_vegetarian=False, author=self.user) self.menu.dish.add(self.dish_meat) self.serializer_input = Menu.objects.all() self.serializer = MenuSerializer(data=self.serializer_input, many=True) self.serializer.is_valid() def test_contain_expected_fields(self): data = self.serializer.data[0] self.assertCountEqual( data.keys(), ['id', 'name', 'description', 'created_at', 'updated_at', 'dish']) def test_contain_expected_values(self): data = self.serializer.data[0] self.assertEqual(data['id'], self.menu.id) self.assertEqual(data['name'], self.menu.name) self.assertEqual(data['description'], self.menu.description) self.assertEqual(data['created_at'], datetime.strftime(self.menu.created_at, "%Y-%m-%d")) self.assertEqual(data['updated_at'], datetime.strftime(self.menu.updated_at, "%Y-%m-%d")) self.assertTrue(self.menu.dish.first().id in data['dish'])
def get(self, request): """ get方法 """ try: user_id = get_user_id(request) user_menu_objects = Menu.objects.filter(user_id=user_id, if_show=True) menu_ids = user_menu_objects.values_list('id', flat=True) calories = DishOrder.objects.filter(menu__in=menu_ids).values('menu_id').\ annotate(calorie=Sum(F('mass') * F('dish__calorie'))).values('menu_id', 'calorie') user_menus = MenuSerializer(user_menu_objects, many=True).data[:10] for menu in user_menus: menu['calorie'] = list(filter(lambda x: x['menu_id'] == menu['id'], calories))[0]['calorie'] except Exception as e: return self.error(err=str(e)) return self.success(data={'user_menus': user_menus})
def list_menu(request): """ 菜单列表 --- serializer: menu.serializers.MenuSerializer omit_serializer: false responseMessages: - code: 200 message: OK - code: 401 message: Not authenticated """ serializer = MenuSerializer(request.current_restaurant.menus.all(), many=True) return Response(serializer.data, status=status.HTTP_200_OK)
def test_retrieve_menus(self): """Test retrieving menus""" option1 = Option.objects.create( description='Corn pie, Salad and Dessert') option2 = Option.objects.create( description='Chicken Nugget Rice, Salad and Dessert') menu = Menu.objects.create(date=datetime.date.today()) menu.options.add(option1) menu.options.add(option2) res = self.client.get(MENUS_URL) menus = Menu.objects.all().order_by('-date') serializer = MenuSerializer(menus, many=True) self.assertEqual(res.status_code, status.HTTP_200_OK) self.assertEqual(res.data, serializer.data)
def setUp(self): self.menu_attributes = { 'name': 'Test name', 'description': 'Test description', } self.serializer_data = { 'name': 'Test name 1', 'description': 'Test description 1', } self.factory = APIRequestFactory() self.request = self.factory.get('api/menu/') self.serializer_context = { 'request': Request(self.request), } self.menu = Menu.objects.create(**self.menu_attributes) self.serializer = MenuSerializer(instance=self.menu, context=self.serializer_context)
def menu_detail(request, pk, format=None): try: menu = Menu.objects.get(pk=pk) except Menu.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) if request.method == 'GET': serializer = MenuSerializer(menu) return Response(serializer.data) elif request.method == 'PUT': serializer = MenuSerializer(menu, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) elif request.method == 'DELETE': menu.delete() return Response(status=status.HTTP_204_NO_CONTENT)
def get_menu(request, pk): """ 获取指定菜单 --- serializer: menu.serializers.MenuSerializer omit_serializer: false responseMessages: - code: 200 message: OK - code: 404 message: Not Found - code: 401 message: Not authenticated """ try: menu = Menu.objects.get(pk=pk) except Menu.DoesNotExist: return Response('menu type not found', status=status.HTTP_404_NOT_FOUND) serializer = MenuSerializer(menu) return Response(serializer.data, status=status.HTTP_200_OK)
def get(self, *args, **kwargs): menu = get_object_or_404(Menu, pk=kwargs['pk']) serialized_data = MenuSerializer(menu).data return Response(serialized_data)
def get(self, request, menu_id, format=None): menu = self.get_object(request, menu_id) serializer = MenuSerializer(menu) return Response(serializer.data)
def get(self, request): menu = Menu.objects.all().order_by('id') pg = StandardPageNumberPagination() page_roles = pg.paginate_queryset(queryset=menu, request=request, view=self) serializer = MenuSerializer(instance=page_roles, many=True) return pg.get_paginated_response(serializer.data)#Response(serializer.data)
class RoleSerializer(serializers.ModelSerializer): menu = MenuSerializer(many=True) class Meta: model = Role fields = "__all__"
def get(self, request, pk): # print(request.user) menu = self.get_object(pk) serializer = MenuSerializer(menu) return Response(serializer.data)