def order_Examination(cls, order): # 地址校验 if not cls.check_address(order): raise CustomException('20002', '地址校验不通过') order_diff = cls.check_stock_change(order) # 库存校验,包括锁定库存的修改,比如商品修改数量的处理 # 怎么处理原来没有的商品现在增加了的场景 if not cls.check_stock(order_diff): raise CustomException('20001', '库存不足') # 仓库校验, 包括仓库库存。 如果没有仓库,进行路由和拆单处理(if need) if order['warehouse_id']: if not cls.check_warehouse_stock(order['order_detail'], order['warehouse_id']): raise CustomException('20004', '目的仓库库存不足') else: cls.route(order) # 订单状态修改 已审核 # 跟wms交互 return {'success': True}
def create(self, user_id, token, data, user_name=None): s = ';' user_info = get_user_info(user_id) express_number = s.join(data.get('express_number', [])) stock_in = StockIn(stock_in_type=int(data.get('stock_in_type', 1)), warehouse_id=data['warehouse_id'], express=data.get('express'), express_number=express_number, warehouse_code=data.get('warehouse_code'), warehouse_name=data.get('warehouse_name'), wms_app_key=data.get('wms_app_key'), user_note=data.get('user_note'), estimated_to_arrival=datetime.fromtimestamp( int(data.get('estimated_to_arrival'))), user_id=user_id, user_name=user_name, user_mobile=user_info['phone'], id=IdGenerationService.generate_stock_in_id()) # 获取仓库信息,修改入库单的发货和收货信息 # 可能存在不能获取到信息的情况 warehouse = get_warehouse_by_id(data['warehouse_id'], token) stock_in.sender_phone = data.get('sender_phone', '') stock_in.send_name = data.get('sender_name', '') stock_in.recipient_phone = warehouse['warehouse_recipient_contact'] stock_in.recipient_name = warehouse['warehouse_recipient_name'] # 如果是退货入库,必须关联退货订单 if int(data['stock_in_type']) == 2: try: order = Order.objects.get(id=data['order_id']) stock_in.order_code = order.order_code except AttributeError: raise CustomException('10003', 'order_id not exist') except ObjectDoesNotExist: raise CustomException('10009') if not data.get('skues'): raise CustomException('10020', '请填写商品信息') create_stock_in_details = [] for sku_info in data['skues']: sku = Sku.objects.get(id=sku_info['sku_id']) stock_in_detail = StockInDetail(quantity=sku_info['quantity'], sku_id=sku_info['sku_id'], stock_in_id=stock_in.id, sku_name=sku.sku_name, sku_spec=sku.specification, bar_code=sku.bar_code, item_code=sku.item_code, user_id=user_id) create_stock_in_details.append(stock_in_detail) stock_in.save() StockInDetail.objects.bulk_create(create_stock_in_details) stock_in.stock_in_details = create_stock_in_details # data['warehouse_id'] # EntryOrder(custom_id='xiaobanma').\ # sync_to_cop(user_id, stock_in) EntryOrder(custom_id=data['warehouse_id']).\ sync_to_cop(user_id, stock_in) return stock_in
def update(cls, request): result = {'success': False, 'error_code': '10003'} token = request.META.get('HTTP_TOKEN') if token: token_json = jwt_token_certify(token) if token_json and isinstance(token_json, dict): user_id = token_json['u'] request_data = request.data if 'store_id' in request_data: store_id = request_data['store_id'] store = None try: store = Store.objects.get(id=store_id) except BaseException: raise CustomException('10003', '店铺不存在') store_account = { 'app_key': store.app_key, 'app_secret': store.app_secret, 'store_key': store.store_key, 'access_token': store.access_token } goods_num = interface.get_product_total( store.platform_name, store_account) pages = common_params.get_pages(goods_num) index = 1 for i in range(pages): pageno = i + 1 product_page = interface.get_product_list( store.platform_name, store_account, pageno) for product in product_page: oms_goods = interface.to_oms_sku( store.platform_name, user_id, product) sku = Sku(**oms_goods) sku.save() print("index = %s, 商品标识 = %s, 商品编号 = %s" % (index, oms_goods["item_code"], oms_goods["sku_name"])) index += 1 # 返回的结果 result_data = { 'user_id': user_id, 'store_id': store_id, 'goods_num': goods_num } # thread_goods = GoodsThread(platform, goods_num, store_account) # thread_goods.start() return result_data else: raise CustomException('10003', '店铺不存在') elif token_json is None: raise CustomException('10012', 'token不存在') elif token_json is False: raise CustomException('10011', 'token 认证失败') else: raise CustomException('10010', 'token不存在') return result
def order_check(self, user_id, order_id): # 获取订单 order = self.get(user_id=user_id, order_id=order_id) if order.order_status != 10: raise CustomException( 50001, '%s状态无法审核' % str(order.get_order_status_display())) if order.order_mark == 40: raise CustomException(50002, '订单审核失败:该订单已锁定') # if order.order_status != 10 or order.order_mark == 40: # raise CustomException('10011', '该订单无法审核') validation_errors = [] # 校验 地址 address = order.consignee_province + order.consignee_city +\ order.consignee_area + order.consignee_detail if not self.validate_address(address): raise CustomException(50003, '订单审核失败:地址非法') # validation_errors.append('invalid address') # 获取 订单sku id:数量 sku_infoes = {} for order_detail in order.order_details: if order_detail.sku_id not in sku_infoes: sku_infoes[order_detail.sku_id] = order_detail.quantity else: sku_infoes[order_detail.sku_id] += order_detail.quantity # 校验 库存 for sku_info_id, sku_info_quantity in sku_infoes.items(): inventories = self.\ get_inventory(sku_id=sku_info_id, warehouse_id=order.warehouse_id) inventory = sum([i.available_quantity for i in inventories]) if inventory < sku_info_quantity: raise CustomException(50004, '订单审核失败:库存不足') # validation_errors.\ # append('sku: %s inventory shortage' % sku_info_id) # 若没有校验错误,则更改订单状态,否则抛出异常 if not validation_errors: print('审核通过') order.order_status = 20 # 审核通过 order.order_status_info = '已审核' order.order_mark = 10 # 正常订单 order.operate_time = datetime.now() # 锁定库存 InventoryService.lock_inventory(order_id=order_id) order.save() else: raise CustomException(error_code='10010', error_message=validation_errors) return order
def comfirm_withdraw(self, user_id, withdraw_id): ''' 提现 ''' withdraw = Withdraw.objects.\ get(id=withdraw_id, user_id=user_id) if withdraw.status != 1: raise CustomException(10010, '【%s】状态下不允许提现' % str(withdraw.status)) tf = self.get_pingpp().Transfer.create( order_no=withdraw.order_no, channel=withdraw.channel, amount=withdraw.amount, currency='cny', app=dict(id=settings.PINGXX_APPID), type='b2c', recipient=withdraw.recipient, extra=dict(recipient_name=withdraw.extra['recipient_name']), description=withdraw.description) withdraw.status = tf['status'] withdraw.tfansfer_id = tf['id'] withdraw._object = tf['object'] withdraw.created = tf['created'] withdraw.time_tfansferred = tf['time_tfansferred'] withdraw.livemode = tf['livemode'] withdraw.batch_no = tf['batch_no'] withdraw.amount_settle = tf['amount_settle'] withdraw.tfansaction_no = tf['transaction_no'] withdraw.failure_msg = tf['failure_msg'] withdraw.extra = tf['extra'] withdraw.status_info = '提现成功' if tf.status == 'failed': withdraw.status_info = '提现失败' return withdraw
def list_warehouse_inventory(self, user_id, token, warehouse_id=None, params=None): ''' 共享仓用户查看仓库下的库存 ''' page_size = int(params.get('page_size', 10)) own_warehouses = list_own_warehouse(token) warehouse_ids = [w['warehouse_id'] for w in own_warehouses] queryset = None if warehouse_id and (warehouse_id in warehouse_ids): queryset = SkuWarehouse.objects.\ select_related('sku').\ filter(warehouse_id=warehouse_id, is_deleted=False) elif warehouse_id: raise CustomException(10013, '仓库不存在') else: queryset = SkuWarehouse.objects.\ select_related('sku').\ filter(warehouse_id__in=warehouse_ids, is_deleted=False) if params.get('sku_name'): print(params.get('sku_name')) queryset = queryset.\ filter(sku__sku_name__contains=params.get('sku_name')) elif params.get('item_code'): queryset = queryset.\ filter(sku__item_code__contains=params.get('item_code')) elif params.get('bar_code'): queryset = queryset.\ filter(sku__bar_code__contains=params.get('bar_code')) paginator = Paginator(queryset, page_size) return paginator
def decorated_function(request, *args, **kwargs): token = request.META.get('HTTP_TOKEN') if not token: raise CustomException(20000, 'Token不存在') else: # pub_path = os.path\ # .join(os.getcwd(), 'cmm/config/public_key.pem') # pub_pem = open(pub_path).read() # pub_key = RSA.importKey(pub_pem) user = jwt.decode(token, settings.TOKEN_KEY, ['HS256']) if time.time() > user['expire']: raise CustomException(20002, 'Token过期') else: user['token'] = token request.user = user return f(request, *args, **kwargs)
def get_item_code(cls, user_id, item_code): try: sku = Sku.objects.get(user_id=user_id, item_code=item_code) serializer = SkuSerializer(sku) return serializer.data except Exception as e: raise CustomException('10004', '商品不存在')
def split_order(self, order, combination): create_orders = [] if not combination: raise CustomException("库存不足,无法发货") if len(combination) == 1: order.warehouse_id = [key for key in combination.keys()][0] warehouse = self.warehouses.get(order.warehouse_id) order.is_splited = False # 指定仓库地址 为 发货地址 self.set_warehouse(order, warehouse) # 锁定仓库的可用库存 InventoryService.lock_inventory(order.id, order.warehouse_id) express = self.get_recommand_express(warehouse['express']) order.logistics_name = express['express_name'] order.logistics_code = express['express_code'] order.save() DeliveryOrder(custom_id=order.warehouse_id, id=order.id).sync_to_cop(order) create_orders.append(order) else: # 需要拆单 order.is_splited = True order.save() # 先把锁定的库存换会去 InventoryService.clear_locked_inventory(order.id) create_order_details = [] for warehouse, skues in combination.items(): # 一次循环,拆成一笔订单 _order = self.copy_order(order) _order.warehouse_id = warehouse self.set_warehouse(_order, self.warehouses.get(warehouse)) express = self.get_recommand_express(warehouse['express']) _order.logistics_name = express['express_name'] _order.logistics_code = express['express_code'] _order.save() create_orders.append(_order) # 获取仓库里的sku 数量,创建order_detail for sku in skues: for order_detail in order.order_details: if order_detail.sku_id == sku[0]: _order_detail = OrderDetail(sku_id=sku[0], quantity=sku[1], order_id=_order.id) _order_detail.save() create_order_details.append(_order_detail) # 先锁定总库存 InventoryService.lock_inventory(_order.id) # 然后锁定仓库的库存 InventoryService.lock_inventory(_order.id, _order.warehouse_id) # OrderDetail.objects.bulk_create(create_order_details) # 保存子订单和主订单之间的关系 for idx, sub_order in enumerate(create_orders): split_order = SplitCombineOrder(sub_order_sequence=idx, new_order=sub_order.id, original_order=order.id, is_splited=True) split_order.save() return create_orders
def check(self, data, store_ids): # 满元赠 if data.get('rule_type') == 1: exist = ActivityRule.objects.\ filter(rule_type=1, is_deleted=False, is_expired=False, store_id__in=store_ids) if exist: raise CustomException("店铺下已存在正在进行的满元赠活动")
def create(cls, store_form): try: if 'user_id' not in store_form: raise CustomException('10001', '用户不存在') if 'plat_id' not in store_form: raise CustomException('10003', '平台不存在') owner = store_form['user_id'] plat = Plat.objects.get(id=store_form['plat_id']) store_form.pop('plat_id') store = Store(**store_form) store.user_id = owner store.platform = plat store.save() except Exception as e: print(e) raise CustomException('10003', '平台不存在') return None
def verify_data(cls, store_form): if 'user_id' not in store_form: raise CustomException('10001', '用户不存在') if 'plat_id' not in store_form: raise CustomException('10003', '平台不存在') owner = store_form['user_id'] try: plat = Plat.objects.get(id=store_form['plat_id']) store_form.pop('user_id') store_form.pop('plat_id') store = Store(**store_form) store.user_id = owner store.platform = plat store.save() except Exception as e: raise CustomException('10003', '平台不存在') return True
def create(cls, sku_form): if 'user_id' not in sku_form: raise CustomException('10001', '用户不存在') owner = sku_form['user_id'] sku_form.pop('user_id') sku = Sku(**sku_form) sku.user_id = owner sku.save() return None
def get_warehouse_by_id(warehouse_id, token=None): headers = {} if token: headers = {'token': token} resp = get(settings.GET_WAREHOUSE_BY_ID_URL + warehouse_id, headers=headers) if resp and resp['result'] is not None: return transfer_warehouse(resp['result']) elif not resp['result']: raise CustomException(10010, '获取不到仓库信息') return None
def check_warehouse_stock(cls, order_detail_list, warehouse_id): for order_detail in order_detail_list: try: sku_warehouse = SkuWarehouse.objects.get( sku__id=order_detail['sku_id'], warehouse__id=warehouse_id) if int(order_detail['quantity'] ) > sku_warehouse.available_quantity: return False except Exception as e: raise CustomException('10001', str(e)) return True
def delete(self, activity_rule_id, user_id): activity_rule = ActivityRule.objects.\ get(user_id=user_id, id=activity_rule_id) if activity_rule.is_enabled: raise CustomException('10012', "活动开启状态无法删除") else: activity_rule.is_deleted = True activity_rule.save() ActivitySku.objects.\ filter(activity_rule_id=activity_rule.id).\ filter(is_deleted=False).\ update(is_deleted=True) return activity_rule
def get_warehouse_by_code(warehouse_code, wms_app_key, token=None): headers = {} if token: headers = {'token': token} param = {'warehouse_code': warehouse_code, 'wms_app_key': wms_app_key} resp = requests.get(settings.GET_WAREHOUSE_BY_CODE_URL, params=param, headers=headers) print(resp) resp = resp.json() if resp and resp['result'] is not None: return transfer_warehouse(resp['result']) elif not resp['result']: raise CustomException(10010, '获取不到仓库信息') return None
def get_used_warehouse_operation_info(warehouse_id, token): headers = {'token': token} param = {'warehouse_id': warehouse_id} resp = requests.get( settings.CMM_URL+GET_USED_WAREHOUSE_OPERATION_INFO, params=param, headers=headers) print(resp) resp = resp.json() if resp and resp['result'] is not None: return resp['result'] elif not resp['result']: raise CustomException(10010, '获取不到仓库信息') return None
def set_status_ori(cls, order_code, store_id, status_ori, refund_status_ori): order = Order.objects.\ get(order_code=order_code, store__id=store_id) refund_status_oris = int(refund_status_ori) if refund_status_oris in (0, 1, 2, -1): order.status_ori = status_ori order.refund_status_ori = refund_status_oris if refund_status_oris == 1: cls.refund(order) order.save() return {} else: raise CustomException('20001', '订单状态不合法')
def create(self, data): # 检查平台是否存在 plat = Plat.objects.filter(name=data['platform_name']) if plat: raise CustomException(10004) plat = Plat( name=data['platform_name'], interface=data.get('interface'), callback=data.get('callback'), need_store_key=data.get('need_store_key', False), is_jointed=data.get('is_jointed', False) ) plat.save() # Plat.objects.bulk_create([plat], set_primary_keys=True) # print("=================================") # print(plat.id) # print("==============================") return plat
def lock_count(cls, data): item_code = data['item_code'] user_id = data['user_id'] count = int(data['quantity']) warehouse_id = data['warehouse_id'] try: sku = Sku.objects.get(user_id=user_id, item_code=item_code) if warehouse_id == '0': sku.available_quantity -= count sku.save() else: sku_warehouse = SkuWarehouse.objects.get( warehouse_id=warehouse_id, sku=sku) sku_warehouse.available_quantity -= count sku_warehouse.save() return True except Exception as e: print(e) raise CustomException('10007', '库存不存在')
def details(self, user_id, start_time, end_time, receipt_type=1, page_size=10): ''' 收入明细 :params :receipt_type 1:订单收入 2:仓储收入 ''' print(start_time, end_time) if int(receipt_type) == 1: query_set = OrderReceipt.objects.\ filter(user_id=user_id, created_at__range=(start_time, end_time)) paginator = Paginator(query_set, per_page=page_size) return paginator elif int(receipt_type) == 2: query_set = StorgeReceipt.objects.\ filter(user_id=user_id, created_at__range=(start_time, end_time)) return Paginator(query_set, per_page=page_size) else: raise CustomException(40007, '不支持的收入类型') return None
def details(self, user_id, start_time, end_time, bill_type=1, page_size=10): ''' 账单明细 :params :bill_type 1:发货账单 2:仓储账单 :params : ''' if int(bill_type) == 1: query_set = OrderBill.objects.\ filter(user_id=user_id, created_at__range=(start_time, end_time)) paginator = Paginator(query_set, per_page=page_size) return paginator elif int(bill_type) == 2: query_set = StorgeBill.objects.\ filter(user_id=user_id, created_at__range=(start_time, end_time)) return Paginator(query_set, per_page=page_size) else: raise CustomException(40004, '不支持的账单类型') return None
def withdraw_balance(self, user_id, amount, channel, recipient, recipient_name): ''' 余额提现 ''' balance = self.show_balance(user_id) if amount > balance: raise CustomException(40003, '提现金额大于账户余额') description = '仓妈咪账户余额提现' withdraw = Withdraw(withdraw_type=1, user_id=user_id, amount=amount, order_no=str(int(time.time())), channel=channel, currency='cny', app=settings.PINGXX_APPID, recipient=recipient, extra=json.dumps( dict(recipient_name=recipient_name)), description=description) withdraw.save() logger.info('用户{0},{1}:申请提现:{2}'.format(user_id, recipient_name, amount)) return withdraw
def withdraw(self, user_id, amount, channel, recipient, recipient_name): ''' 保证金提现 ''' deposit = self.show_deposit(user_id) if deposit < amount: raise CustomException(40008, '提现金额大于保证金余额!') description = '仓妈咪账户保证金提现' self.deduct_deposit(user_id, amount) withdraw = Withdraw(withdraw_type=2, user_id=user_id, amount=amount, order_no=str(int(time.time())), channel=channel, currency='cny', app=settings.PINGXX_APPID, recipient=recipient, extra=json.dumps( dict(recipient_name=recipient_name)), description=description) withdraw.save() logger.info('用户{0},{1}:提现保证金:{2}'.format(user_id, recipient_name, amount)) return withdraw
def entry_orders(self, user_id, token, params=None, warehouse_id=None): ''' 入库任务 ''' page_size = int(params.get('page_size', 10)) warehouses = self.get_shared_warehouse(token) warehouse_ids = [w['warehouse_id'] for w in warehouses] queryset = None stock_in_detail = StockInDetail.objects.\ filter(is_deleted=False) if warehouse_id and warehouse_id in warehouse_ids: # TODO 根据抵达时间排序 queryset = StockIn.objects.\ prefetch_related( Prefetch('stockindetail_set', queryset=stock_in_detail, to_attr='stock_in_details') ).\ filter(~Q(stock_in_status='NEW'), warehouse_id=warehouse_id) elif warehouse_id: raise CustomException(10013, '仓库不存在') else: queryset = StockIn.objects.\ prefetch_related( Prefetch('stockindetail_set', queryset=stock_in_detail, to_attr='stock_in_details') ).\ filter(~Q(stock_in_status='NEW'), warehouse_id__in=warehouse_ids) if params.get('stock_in_code'): # 蘑菇搜索 queryset = queryset.\ filter(stock_in_code__contains=params.get('stock_in_code')) elif params.get('express_code'): pass paginator = Paginator(queryset, per_page=page_size) return paginator
def set_status(cls, order_code, store_id, status): # TODO temp order = Order.objects.\ get(order_code=order_code, store__id=store_id) order_details = OrderDetail.objects.\ filter(order=order, is_deleted=False).\ select_related('sku') order = Order.objects.\ prefetch_related( Prefetch('order_detail', queryset=order_details, to_attr='order_details') ).\ select_related('store').\ get(order_code=order_code, store__id=store_id) status = int(status) if status in (10, 20, 30, 40): order.order_status = status if status == 20: logger.debug('order auto approved') order.order_status = status order.operate_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())) if not order.is_splited: logger.debug('send to wms, order_id : ' + order.id) order = cls.set_warehouse_info(order) # TODO custom_id warehouse_id DeliveryOrder(custom_id=order.warehouse_id, id=order.id).sync_to_cop(order) order.save() elif status in (10, 30, 40): order.order_status = status order.save() return {} else: raise CustomException('20001', '订单状态不合法')
def create(self, user_id, store_ids, data): try: stores = Store.objects.\ filter(id__in=store_ids, user_id=user_id) # 活动检查 self.check(data, store_ids) activities = [] activity_skues = [] print(stores) for store in stores: # 满元赠 if int(data.get('rule_type', 0)) == 1: # 活动规则创建 activity_rule = ActivityRule( title=data['title'], rule_type=int(data['rule_type']), begin_date=data['begin_date'], end_date=data['end_date'], accord_cost=data.get('accord_cost', 0), is_times=data.get('is_times', False), store=store, user_id=user_id) activity_rule.save() activity_rule.gifts = [] # 赠品添加 for gift_data in data['gifts']: if gift_data.get('sku_id', ''): gift = Sku.objects.get(id=gift_data['sku_id']) activity_gift = ActivitySku( is_gift=True, count=gift_data['count'], sku=gift, activity_rule=activity_rule) activity_skues.append(activity_gift) activity_rule.gifts.append(activity_gift) activities.append(activity_rule) elif int(data.get('rule_type', 0)) == 2: # 满件赠 activity_rule = ActivityRule( title=data['title'], rule_type=int(data['rule_type']), begin_date=data['begin_date'], end_date=data['end_date'], accord_amount=data.get('accord_amount', 0), store=store, user_id=user_id) activity_rule.save() activities.append(activity_rule) activity_rule.skues = [] for sku_data in data['skues']: if sku_data.get('sku_id', ''): sku = Sku.objects.get(id=sku_data['sku_id']) activity_sku = ActivitySku( is_gift=False, sku=sku, activity_rule=activity_rule) activity_skues.append(activity_sku) activity_rule.skues.append(activity_sku) activity_rule.gifts = [] # 赠品添加 for gift_data in data['gifts']: if gift_data.get('sku_id', ''): gift = Sku.objects.get(id=gift_data['sku_id']) activity_gift = ActivitySku( is_gift=True, count=gift_data['count'], sku=gift, activity_rule=activity_rule) activity_skues.append(activity_gift) activity_rule.gifts.append(activity_gift) # 批量创建 # bulk_create 不支持mysql生成id(pstgresql) # ActivityRule.objects.bulk_create(activities) for _ in activities: print(_.id) print("---------------") ActivitySku.objects.bulk_create(activity_skues) return activities except Exception as e: print("==================") print(e) raise CustomException(10010)
def check_invalid(self, store): ''' 检查店铺配置 ''' if not store.app_key or not store.app_secret: raise CustomException(40009, 'app key 或 app seceret不存在') if store.platform.need_store_key and not store.store_key: raise CustomException(40010, 'store key不存在')
def create_order(cls, order): logger.debug('==================================') logger.debug(order) logger.debug('==================================') o = Order() # if order.get('order_id', False): # o.id = order['order_id'] # 按照规则生成order的id o.id = IdGenerationService.generate_order_id() o.consignee_country = order['consignee_country'] store_id = order['store_id'] user_id = order['user_id'] user_info = get_user_info(user_id) o.user_name = user_info['nickname'] o.user_id = user_id try: store = Store.objects.get(id=store_id) except: raise CustomException('10001', '店铺不存在') else: o.store = store order_status_info = order.get('order_status_info', '') if order_status_info: o.order_status_info = order_status_info else: o.order_status_info = '10' o.order_status = order.get('order_status', '10') o.mark_reason = order['mark_reason'] o.express_note = order['express_note'] o.buyer_note = order['buyer_note'] o.goods_price = order['goods_price'] o.express_type = order['express_type'] o.status_ori = order['status_ori'] o.quantity = order['quantity'] o.consignee_detail = order['consignee_detail'] o.express_fee = order['express_fee'] o.consignee_country = order['consignee_country'] o.order_code = order['order_code'] o.consignee_area = order['consignee_area'] o.refund_status_ori = order['refund_status_ori'] o.total_price = order['total_price'] o.express_number = order['express_number'] o.consignee_phone = order['consignee_phone'] o.consignee_city = order['consignee_city'] o.consignee_province = order['consignee_province'] o.consignee_name = order['consignee_name'] o.pay_time = order['pay_time'] o.add_time = order['add_time'] if order.get('warehouse_id', False): o.warehouse_id = order['warehouse_id'] o.created_at = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())) o.save() for order_detail in order['order_details']: item_code = order_detail['item_code'] sku = Sku.objects.get(item_code=item_code, user_id=user_id) od = OrderDetail() # od.sku_id = sku.id od.total_price = order_detail['total_price'] # od.order_id = order_detail['order_id'] od.order = o od.sku = sku od.price = order_detail['price'] # od.order_detail_id = order_detail['order_detail_id'] od.quantity = order_detail['quantity'] od.save() return {'order_id': o.id}