def post(self, request): data = request.data booking = BookingStatus.booking_status(data['appointment_at']) if booking[data['meal_type'] - 1] > 0: return Response({'msg': '预约失败,预约已截止', 'code': -1}) data['wx_id'] = request.user.wx_id s = OrderSerializer(data=data) if s.is_valid(): s.save() return Response({'msg': '预约成功', 'code': 0}) else: # 判断是否已经存在了这条数据 order = models.Order.objects.filter(appointment_at=data['appointment_at'], wx_id=data['wx_id'], meal_type=data['meal_type']).first() if order: # 如果存在这条预约 if order.is_delete: # 如果已删除,恢复这条数据 obj = models.Order.objects.get(pk=order.id) # 找到这条订单记录 s = OrderSerializer(instance=obj, data={'is_delete': 0}, partial=True) # 序列化这条订单实例 if s.is_valid(): # 验证格式 s.save() return Response({'msg': '预约成功', 'code': 0}) else: return Response({'msg': '预约失败', 'code': -1}) else: return Response({'msg': '预约失败,此餐已预约,不能重复预约', 'code': -1}) else: return Response({'msg': '预约失败', 'code': -1})
def post(self, request): ret = {'code': 200, 'msg': '新增订单成功', 'data':{}} try: new_order = OrderSerializer(data=request.data) # 查询预约是否冲突 # 检查一:user + order_date + order_time_period queryset1 = models.Order.objects.filter(Q(user_account=request.user) & Q(order_date=request.data.get('order_date')) & Q(order_time_period=request.data.get('order_time_period'))) # 检查二:good_id + order_date + order_time_period queryset2 = models.Order.objects.filter(Q(good_id=request.data.get('good_id')) & Q(order_date=request.data.get('order_date')) & Q(order_time_period=request.data.get('order_time_period'))) if new_order.is_valid(): if queryset1.count() == 0 and queryset2.count() == 0: new_order.save() # 先save(),再调用 ret['data'] = new_order.data else: if queryset1.count() != 0: ret['code'] = 201 ret['msg'] = '用户该时间段已有预约:' + str(new_order.errors) else: ret['code'] = 202 ret['msg'] = '此物品该时间段已有预约:' + str(new_order.errors) else: ret['code'] = 203 ret['msg'] = '数据错误: ' + str(new_order.errors) except Exception as e: ret['code'] = 204 ret['msg'] = '新增订单失败' + str(e) changeOrderStatus() return JsonResponse(ret, json_dumps_params={'ensure_ascii':False})
def put(self, request, order_id, format=None): order = self.get_object(id=order_id, owner=request.user) serializedOrder = OrderSerializer(order, data=request.data, exclude=('status','owner','assigned_to')) if serializedOrder.is_valid(): serializedOrder.save() return Response({'order':serializedOrder.data}, status=status.HTTP_200_CREATED) else: return Response({'error':serializedOrder.errors}, status=status.HTTP_400_BAD_REQUEST)
def put(self, request): order = models.Order.objects.filter(pk=request.data['id']).first() # 检查这个预约是不是自己 if order.wx_id != request.user.wx_id: return Response({"msg": "您不可以取消其他人的预约", "code": -1}) # todo 判断是否已经截止 s = OrderSerializer(instance=order, data={'is_delete': 1}, partial=True) # 序列化这条订单实例 if s.is_valid(): s.save() return Response({'msg': '取消预约成功', 'code': 0})
def get_order_by_pickup_no(request): if request.method == 'POST': try: pickup_data = JSONParser().parse(request) pickup_obj = PickUp.objects.filter( pickup_no=pickup_data['pickup_no'])[0] order_list = Order.objects.filter( supplier_code=pickup_obj.supplier_code, plant_code=pickup_obj.plant_code, due_date__year=pickup_obj.due_date.year, due_date__month=pickup_obj.due_date.month, due_date__day=pickup_obj.due_date.day, route_code=pickup_obj.route_code, route_trip=pickup_obj.route_trip, is_route_completed=True, is_part_completed=True, is_deleted=False) order_serializer = OrderSerializer(order_list, many=True) serializer = serializerMapping.mapping_serializer_list( Order_list_Serializer_DTO, order_serializer.data, "success", None, "", None, None) return Response(serializer.data, status=status.HTTP_200_OK) except Exception as e: serializer = serializerMapping.mapping_serializer_list( Order_list_Serializer_DTO, None, "Error", e, None, None, None) return Response(serializer.data, status=status.HTTP_200_OK)
def test_retrieve_order(self): Order.objects.create( user=self.user, seller_name='miss lina', seller_phone='0501234590', seller_location='https://goo.gl/maps/DKBH5uEAH5Sw7FVX6', customer_name='miss dana', customer_phone='0501035590', customer_location='https://goo.gl/maps/GXJ33PdEjoaD1p1u9', ) Order.objects.create( user=self.user, seller_name='miss lina', seller_phone='0501234590', seller_location='https://goo.gl/maps/DKBH5uEAH5Sw7FVX6', customer_name='miss dana', customer_phone='0501035590', customer_location='https://goo.gl/maps/GXJ33PdEjoaD1p1u9', ) res = self.client.get(ORDER_URL) orders = Order.objects.all().order_by('-seller_name') serializer = OrderSerializer(orders, many=True) self.assertEqual(res.status_code, status.HTTP_200_OK) self.assertEqual(res.data, serializer.data)
def get(self, request, *args, **kwargs): """ GET - получение информации по заказам :param request: в Header нужно добавить Token, например так: { key: 'Authorization', value: 'Token 80d57ddd904f358b00375f500d74d181fdbc9a58' } :return: Информация по заказу """ if not request.user.is_authenticated: return JsonResponse({ 'Status': False, 'Error': 'Log in required' }, status=403) order = Order.objects.filter(user_id=request.user.id).exclude( status='basket').prefetch_related( 'ordered_items__product_info__product__category', 'ordered_items__product_info__product_parameters__parameter' ).select_related('profile').annotate(total_sum=Sum( F('ordered_items__quantity') * F('ordered_items__product_info__price'))).distinct() serializer = OrderSerializer(order, many=True) return Response(serializer.data)
def get_comment_by_user(request): if request.method == 'POST': ret = {"code": 200, "msg": "获取用户评论成功"} try: # Authtication()要先实例化 account, token_obj = Authtication().authenticate(request=request) # 获得用户的所有订单 queryset = Order.objects.filter(user_account=account).all() order_list = OrderSerializer(queryset, many=True).data data = [] for item in order_list: single = {} single['good_name'] = item.get('good_name') single['order_date'] = item.get('order_date') single['order_time_period_name'] = item.get( 'order_time_period_name') single['order_date'] = item.get('order_date') # 获取评论内容 queryset = CommentsInfo.objects.filter( order=item.get('id')).first() if queryset is not None: comment_obj = CommentsInfoSerializers(queryset) single['comment_content'] = comment_obj.data.get( 'comment_content') data.append(single) ret['count'] = len(data) ret['data'] = data except Exception as e: ret['code'] = 201 ret['msg'] = '获取用户评论失败:' + str(e) return JsonResponse(ret, json_dumps_params={'ensure_ascii': False})
def get(self, request, control_number, format=None): queryset = Order.objects.filter( ~Q(task_status='completed'), console=control_number, ) serializer = OrderSerializer(queryset, many=True) return JsonResponse(serializer.data, safe=False, status=200)
class DriverSerializer(serializers.ModelSerializer): password = serializers.CharField(min_length=8, max_length=50, write_only=True) token = serializers.CharField(max_length=255, read_only=True) orders = OrderSerializer(many=True, read_only=True) photos = PhotoSerializer(many=True, read_only=True) phones = DriverPhone(many=True) class Meta: model = Driver fields = "__all__" read_only_fields = ('rate', 'total_orders', 'orders_this_month', 'salary', 'is_deleted') depth = 1 def create(self, validated_data): phones = validated_data.pop('phones') driver = Driver.objects.create(**validated_data) for phone in phones: Phone.objects.create(person=driver, **phone) return driver def update(self, instance, validated_data): phones = validated_data.pop('phones') instance.name = validated_data.get('name', instance.name) instance.email = validated_data.get('email', instance.email) instance.username = validated_data.get('username', instance.username) instance.snn = validated_data.get('snn', instance.snn) instance.save() for phone in phones: Phone.objects.create(person=instance, **phone) return instance
class TableDetailSerializer(serializers.ModelSerializer): order = OrderSerializer(many=True) class Meta: model = Table fields = ['id', 'area', 'status', 'order']
def order_status(request, pk): try: order = Order.objects.get(pk=pk) except Order.DoesNotExist: return HttpResponse(status=404) if request.method == 'PUT': product = Product.objects.get(pk=order.product_id) if order.status == 0: product.quantity -= 1 product.save() if order.attribute_id: productAttribute = ProductAttribute.objects.get( pk=order.attribute_id) productAttribute.quantity -= 1 productAttribute.save() elif order.status == 1: # Waiting shipping order & Increse fund organization = Organization.objects.get(pk=product.organization_id) organization.fund += order.price organization.save() if order.status < 5: order.status += 1 order.save() serializerOrder = OrderSerializer(order) return JsonResponse(serializerOrder.data)
def order_slip(request, pk): try: order = Order.objects.get(pk=pk) except Order.DoesNotExist: return HttpResponse(status=404) if request.method == 'POST': slip = request.FILES['slip'] filename_slip, file_extension = os.path.splitext(slip.name) nameSlip = uuid.uuid4().hex + file_extension fs = FileSystemStorage() filename = fs.save(nameSlip, slip) storage_client = storage.Client() bucket_name = 'mejai' bucket = storage_client.bucket(bucket_name) blob = bucket.blob('bank/transfer/slip/' + nameSlip) blob.upload_from_filename(filename=filename) blob.make_public() fs.delete(nameSlip) order.slip = blob.public_url order.save() serializerOrder = OrderSerializer(order) return JsonResponse(serializerOrder.data)
class UserSerializer(serializers.ModelSerializer): Order = OrderSerializer(read_only=True, many=True) class Meta: model = User fields = ('id', 'email', 'password', 'first_name', 'last_name', 'city', 'address1', 'address2', 'zip_code', 'contact_num', 'date_joined', 'Order')
def put(self, request): ret = {'code': 200, 'msg': None} try: result = json.loads(request.body) order_obj = models.Order.objects.get(pk=int(result.get('order_id'))) # instance=要更新的对象 new_order = OrderSerializer(instance=order_obj, data=request.data) if new_order.is_valid(): new_order.save() ret['msg'] = '编辑成功' else: ret['code'] = 201 ret['msg'] = '数据错误: ' + str(new_order.errors) except Exception as e: ret['code'] = 202 ret['msg'] = '编辑失败' + str(e) return JsonResponse(ret, json_dumps_params={'ensure_ascii':False})
def getOrderByKey(good_id, order_date): queryset = models.Order.objects.filter(Q(good_id_id=good_id) & Q(order_date=order_date)).all() result = OrderSerializer(queryset, many=True) unavailabe_period = [] for item in result.data: unavailabe_period.append(item.get('order_time_period')) return result.data, unavailabe_period
def test_filter_order_by_status(self): """Test filtering order by status""" Pizza.objects.create(flavour='Dessert', prices={ "S": 10.00, "M": 15.00, "L": 20.00 }) Pizza.objects.create(flavour='Vegan', prices={ "S": 10.00, "M": 15.00, "L": 20.00 }) Pizza.objects.create(flavour='Ankara', prices={ "S": 10.00, "M": 15.00, "L": 20.00 }) Pizza.objects.create(flavour='Bali', prices={ "S": 10.00, "M": 15.00, "L": 20.00 }) pizzas = Pizza.objects.all().order_by('-flavour') order1 = create_orders(pizzas[:2], self.user, status='I') order2 = create_orders(pizzas[:2], self.user, status='P') order_serializer1 = OrderSerializer(order1, many=True) order_serializer2 = OrderSerializer(order2, many=True) res = self.client.get(ORDER_URL, {'status': 'I,P'}) self.assertEqual(res.status_code, status.HTTP_200_OK) self.assertIn(order_serializer1.data[0], res.data) self.assertIn(order_serializer1.data[1], res.data) self.assertIn(order_serializer2.data[0], res.data) self.assertIn(order_serializer2.data[1], res.data)
class DriverAdmin(serializers.ModelSerializer): orders = OrderSerializer(many=True, read_only=True) class Meta: model = Driver fields = ('name', 'email', 'username', 'snn', 'is_deleted', 'time_created', 'rate', 'total_orders', 'orders_this_month', 'salary', 'orders') depth = 1
def get(self, request, *args, **kwargs): """ Override the get method and get orders list of current user. """ # get user orders queryset. user_orders = request.user.orders.all() serializer = OrderSerializer(user_orders, many=True, context={"request": self.request}) return Response(serializer.data)
def test_order_object_bundle(self): """ Test to verify order object bundle """ response = self.client.get(self.url) self.assertEqual(200, response.status_code) order_serializer_data = OrderSerializer(instance=self.order).data response_data = json.loads(response.content) self.assertEqual(order_serializer_data, response_data)
def post(self, request, control_number, format=None): serializer = OrderSerializer(data=request.data) serializer.set_foreign_key(control_number) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data, status=201) return JsonResponse(serializer.errors, status=400)
def create_orders(request): result_orders = [] # check user authorized if isinstance(request.user, AnonymousUser): return Response( {"detail": "Authentication credentials were not provided."}, status=status.HTTP_401_UNAUTHORIZED) # check user is in group 1 (User) if User.objects.filter(username=request.user.username, groups=(1, )): # get json orders orders = json.loads(request.body).get('orders') for order in orders: order_serializer = OrderSerializer(data=order) # check or raise exception order_serializer.is_valid(raise_exception=True) # if success -> create order and push to result order_serializer.save(owner=request.user) result_orders.append(order_serializer.data) data = {'orders': result_orders} return Response(data, status=status.HTTP_201_CREATED) return Response( {"detail": "You do not have permission to perform this action."}, status=status.HTTP_403_FORBIDDEN)
def post(self, request, format=None): main = self.sum(request) detail = request.data.get('detail') with transaction.atomic(): order_serializer = OrderSerializer(data=main, context={'request': request}) #raise_exception=True出现异常引发数据库回滚 if order_serializer.is_valid(raise_exception=True): order_serializer.save() print(order_serializer.data) #ordercode = order_serializer.data.get('ordercode') else: return Response(order_serializer.errors, status=status.HTTP_400_BAD_REQUEST) detail_serializer = DetailSerializer(data=detail, many=True) if detail_serializer.is_valid(raise_exception=True): detail_serializer.save() return Response(order_serializer.data, status=status.HTTP_201_CREATED) else: return Response(detail_serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def order_detail(request, pk): ''' Function to return the order data ''' try: cust = Customers.objects.get(pk=pk) except Customers.DoesNotExist: return HttpResponse('Customer id not found', status=404) # Get the order order = Orders.objects.filter(customer_id=cust) # serialize the data serializer_class = OrderSerializer(order, many=True) return Response(serializer_class.data)
def customer_orders(request, pk): try: customer = Customer.objects.get(pk=pk) except Customer.DoesNotExist: return HttpResponse(status=404) if request.method == 'GET': order = Order.objects.filter(buyer_id=pk) serializer = OrderSerializer(order, many=True) data = {} data['data'] = serializer.data data['userId'] = int(pk) return JsonResponse(data, safe=False)
def covert_data_list_to_serializer_list(pickup_list): pickup_return_list = [] for pickup_obj in pickup_list: order_serializer_obj = OrderSerializer() order_serializer_obj.pickup_no = pickup_obj[0] order_serializer_obj.supplier_code = pickup_obj[1] order_serializer_obj.plant_code = pickup_obj[2] order_serializer_obj.route_code = pickup_obj[3] order_serializer_obj.route_trip = pickup_obj[4] order_serializer_obj.due_date = pickup_obj[5] order_serializer_obj.order_count = pickup_obj[6] pickup_return_list.append(order_serializer_obj) return pickup_return_list
class BookingDetailSerializer(serializers.ModelSerializer): room = RoomSerializer(read_only=True) room_id = serializers.PrimaryKeyRelatedField(queryset=Room.objects.all(), source='room', write_only=True) order_set = OrderSerializer(read_only=True, many=True) def create(self, validated_data): return BookingDetail.objects.create(**validated_data) class Meta: model = BookingDetail fields = '__all__'
def get(self, request, *args, **kwargs): try: profile = UserProfile.objects.get(user=request.user) except UserProfile.DoesNotExist: try: profile = EmployeeProfile.objects.get(user=request.user) except EmployeeProfile.DoesNotExist: return Response({'data': 'Please log in!'}) if isinstance(profile, UserProfile): orders = Order.objects.filter(user_profile=profile) serializer = OrderSerializer(orders, many=True) return Response(serializer.data) return Response({'data': 'this is not for you'})
def post(self, request, *args, **kwargs): data = request.data try: order = Order.objects.create( booking_detail=BookingDetail.objects.all().get( pk=data['booking_detail_id']), total_price=data['total_price']) order.service.add(*Service.objects.filter(pk__in=data['service'])) serializer = OrderSerializer(order) except: return Response(status=status.HTTP_400_BAD_REQUEST) return Response(serializer.data, status=status.HTTP_201_CREATED)
def post(self, request): if request.method == 'POST': ret = {"code": 200, "msg": "获取商品评论成功"} body = json.loads(request.body) try: queryset = Order.objects.filter( good_id=body.get('good_id')).all().order_by('-id') order_list = OrderSerializer(queryset, many=True).data data = [] # 自定义分页器 paginator = PageSetting() for item in order_list: single = {} # 获取评论内容 queryset = CommentsInfo.objects.filter( order=item.get('id')).first() if queryset is not None: # 获取用户信息 user_info_obj = models.UserInfo.objects.filter( pk=item.get('user_account')).first() user_info_dic = model_to_dict(user_info_obj) single['head_image'] = user_info_dic['head_image'] single['nickname'] = user_info_dic['nickname'] comment_obj = CommentsInfoSerializers(queryset) single['comment_content'] = comment_obj.data.get( 'comment_content') single['comment_create_time'] = comment_obj.data.get( 'comment_create_time')[0:10] data.append(single) # ret['count'] = len(data) # ret['data'] = data # 计算总页数 total_count = len(data) ret['total_page'] = paginator.cal_total_page( total_count=total_count) page_order = paginator.paginate_queryset(queryset=data, request=request, view=self) ret['count'] = len(page_order) ret['data'] = page_order except Exception as e: ret['code'] = 201 ret['msg'] = '获取商品评论失败:' + str(e) return JsonResponse(ret, json_dumps_params={'ensure_ascii': False})
def get(self, request, *args, **kwargs): try: profile = UserProfile.objects.get(user=request.user) except UserProfile.DoesNotExist: try: profile = RestaurantProfile.objects.get(user=request.user) except RestaurantProfile.DoesNotExist: return Response({"data": "Please log in!"}) if isinstance(profile, UserProfile): orders = Order.objects.filter(userprofile=profile) serializer = OrderSerializer(orders, many=True) return Response(serializer.data) return Response({"data": "NOT FOR YOUR EYES!"})
def post(self, request, format=None): serializedOrder = OrderSerializer(data=request.data,exclude=('status','owner','assigned_to')) if serializedOrder.is_valid(): serializedOrder.save(owner=request.user) return Response({'order':serializedOrder.data}, status=status.HTTP_201_CREATED) return Response({'error':serializedOrder.errors}, status=status.HTTP_400_BAD_REQUEST)