def post(self,request,pk, sec): if sec == 'con': n = Notes.objects.filter(Q(reciever=request.user.id) & Q(connection=pk) & Q(read=True))[:2] f = food.objects.filter(Q(connection=pk) & Q(direction=True)).last() m = movies.objects.filter(Q(connection=pk) & Q(direction=True)).last() a = activities.objects.filter(Q(connection=pk) & Q(direction=True)).last() e = Events.objects.filter(Q(connection=pk) & Q(request=False)& Q(date__gte=datetime.today())).order_by('date')[:5] r = Events.objects.filter(Q(connection=pk) & Q(request=True) & Q(date__gte=datetime.today())).exclude(creator=request.user.id).order_by('date')[:5] return Response({ 'events': PopulatedEventsSerializer(e, many=True).data, 'req': PopulatedEventsSerializer(r, many=True).data, 'note': PopulatedNotesSerializer(n, many=True).data, 'food':FoodSerializer(f).data , 'movie': MovieSerializer(m).data, 'activity': ActivitiesSerializer(a).data}) else : prefetch= Prefetch('connection', queryset=Connections.objects.filter(participants__id=pk)) e = Events.objects.filter(Q(connection__participants__id=pk) & Q(request=False) & Q(date__gte=datetime.today())).prefetch_related(prefetch).order_by('date')[:5] r = Events.objects.filter(Q(connection__participants__id=pk)& Q(request=True) & Q(date__gte=datetime.today())).exclude(creator=pk).prefetch_related(prefetch).order_by('date')[:5] m = movies.objects.filter(Q(user=pk) & Q(direction=True)).order_by('-created_at')[:2] a = activities.objects.filter(Q(user=pk) & Q(direction=True)).order_by('-created_at')[:2] f= food.objects.filter(Q(user=pk) & Q(direction=True)).order_by('-created_at')[:2] n = Notes.objects.filter(Q(reciever=pk) & Q(read=True)).order_by('-created_at')[:2] return Response({ 'events': PopulatedEventsSerializer(e, many=True).data, 'req': PopulatedEventsSerializer(r, many=True).data, 'note': PopulatedNotesSerializer(n,many=True).data, 'food':FoodSerializer(f, many=True).data , 'movie': MovieSerializer(m, many=True).data, 'activity': ActivitiesSerializer(a, many=True).data, })
def post(self, request, *args, **kwargs): meal_id = kwargs['meal_id'] patient_id = kwargs['patient_id'] try: patient = Patients.objects.get(pk=patient_id) except Patients.DoesNotExist: return Response({"Info:": "Patient nto found"}, status=status.HTTP_404_NOT_FOUND) serializer = SubstituteFoodsSerializer(data=request.data) if serializer.is_valid(): foods = str(serializer.validated_data['foods']) quantities = str(serializer.validated_data['quantities']) list_of_foods = list() best_replacements = list() best_qtys = list() if len(foods) > 0 and len(quantities) > 0: foods = foods.split('&') quantities = quantities.split('&') quantities = [float(i) for i in quantities] for element in foods: try: food = Food.objects.get(pk=int(element)) except Food.DoesNotExist: return Response({"Info:": "Food id not found."}, status=status.HTTP_404_NOT_FOUND) list_of_foods.append(food) for food, qty in zip(list_of_foods, quantities): best_food, best_qty = self._findSubstitutes( food, qty, meal_id, patient) best_replacements.append(best_food) best_qtys.append(best_qty) new_serializer = FoodSerializer(best_replacements, many=True) return Response( { "Quantities:": best_qtys, "Replacements": new_serializer.data }, status=status.HTTP_200_OK) else: return Response( {"Info:": "List contains no id or no quantity."}, status=status.HTTP_400_BAD_REQUEST) else: return Response({"Info:": "Some fields are missing."}, status=status.HTTP_400_BAD_REQUEST)
class RestaurantSerializer(serializers.ModelSerializer): foods = FoodSerializer(many=True, read_only=True) followers = StoreFollowerSerializer(many=True, read_only=True) address = AddressSerializer(read_only=True) reviews = ReviewSerializer(many=True, read_only=True) class Meta: model = Restaurant fields = ("id", "name", "content", "restaurant_banner_image", "restaurant_logo", "owner",'address','foods','followers','reviews')
def food_list(request): """ List all food, or create a new entry. """ if request.method == 'GET': foods = Food.objects.all() serializer = FoodSerializer(foods, many=True) return JsonResponse(serializer.data, safe=False) elif request.method == 'POST': data = JSONParser().parse(request) serializer = FoodSerializer(data=data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data, status=201) return JsonResponse(serializer.errors, status=400)
def create(self, request, *args, **kwargs): permission_classes = (permissions.IsAuthenticatedOrReadOnly, ) img = cv2.imdecode( np.fromstring(request.data['image'].read(), np.uint8), cv2.IMREAD_UNCHANGED) t = Deep(img) # return Response(t) serializer1 = FoodSerializer(Food.objects.get(item=t)) owner = self.request.user item = t calories = serializer1.data['calories'] dat = UserCalorie(owner=owner, item=item, calories=calories) dat.save() serializer = UserCalorieSerializer(data=dat) if serializer.is_valid(): serializer.save() return Response(t)
class EventSerializer(serializers.ModelSerializer): organizer_name = serializers.SerializerMethodField() number_of_attendees = serializers.SerializerMethodField() list_of_attendees = serializers.SerializerMethodField() food_order_number_list = serializers.SerializerMethodField() food_types = FoodSerializer(many=True) class Meta: model = Event fields = ('id', 'name', 'organizer_name', 'category', 'food_types', 'list_of_attendees', 'number_of_attendees', 'event_date', 'food_order_number_list', 'url') def get_organizer_name(self, obj): return obj.organizer.user_auth.get_full_name() def get_number_of_attendees(self, obj): numbet_of_participants = 0 for eventattendee in obj.eventattendee_set.all(): numbet_of_participants += \ (eventattendee.number_of_guests + 1) return numbet_of_participants def get_list_of_attendees(self, obj): attendees_names = [] for eventattendee in obj.eventattendee_set.all(): attendees_names.append(eventattendee.attendee.get_full_name()) return attendees_names def get_food_order_number_list(self, obj): food_order_number_list = {} for eventattendee in obj.eventattendee_set.all(): for food_order in eventattendee.food_orders.all(): if food_order.food.food_type in food_order_number_list: food_order_number_list[ food_order.food.food_type] += food_order.number else: food_order_number_list[ food_order.food.food_type] = food_order.number return food_order_number_list
def food_detail(request, pk): """ Retrieve, update or delete a code food. """ try: food = Food.objects.get(pk=pk) except Food.DoesNotExist: return HttpResponse(status=404) if request.method == 'GET': serializer = FoodSerializer(food) return JsonResponse(serializer.data) elif request.method == 'PUT': data = JSONParser().parse(request) serializer = FoodSerializer(food, data=data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data) return JsonResponse(serializer.errors, status=400) elif request.method == 'DELETE': food.delete() return HttpResponse(status=204)
class PortionSerializer(serializers.ModelSerializer): food = FoodSerializer(read_only=True) class Meta: model = Portions fields = ('quantity', 'food')
def post(self, request, *args, **kwargs): patient_id = kwargs['patient'] try: patient = Patients.objects.get(pk=patient_id) except Patients.DoesNotExist: return Response({"Info:": "Patient not found"}, status=status.HTTP_404_NOT_FOUND) if request.user == patient.nutritionist: meal_type = int(kwargs['meal']) patient_restrictions = patient.food_restrictions available_foods = Meal.objects.get(pk=meal_type).foods.exclude( pk__in=patient_restrictions.values_list('id', flat=True)) itens_for_menu = list() max_index = len(available_foods) weights = [0.7, 10, 1, 1, 1] if request.data['calories'] == '0': weights[0] = 0 if request.data['proteins'] == '0': weights[1] = 0 if request.data['carbohydrates'] == '0': weights[2] = 0 if request.data['lipids'] == '0': weights[3] = 0 if request.data['fiber'] == '0': weights[4] = 0 target = [ weights[0] * float(request.data['calories']), weights[1] * float(request.data['proteins']), weights[2] * float(request.data['carbohydrates']), weights[3] * float(request.data['lipids']), weights[4] * float(request.data['fiber']) ] excluding = set() for i in range(0, 8): number = random.randrange(max_index) if number in excluding: tries = 0 while tries < 3 and number in excluding: number = random.randrange(max_index) tries += 1 else: excluding.add(number) itens_for_menu.append(available_foods[number]) found, qty = self._meetInTheMiddle(itens_for_menu, target, weights) serializer = FoodSerializer(found, many=True) return Response({ "Quantities": qty, "Suggestions": serializer.data }, status=status.HTTP_200_OK) else: return Response( {"Info:": "This patient belongs to another nutritionist."}, status=status.HTTP_401_UNAUTHORIZED)