2015-02-05 66 views
-2

有代碼:如何計算總和許多對象

ids = [] 
menu = {} 
for offer in customer_order.split(';'): 
    id, count = offer.split(':') 
    ids.append(id) 
    menu[int(id)] = int(count) 
mList = Goods.objects.filter(id__in=ids, 
          kind_cost=1).values('id', 'cost') 
for item in mList: 
    id = item['id'] 
    cost = item['cost'] 
    menu[id] = menu[id] * cost 
return sum(menu.values()) 

customer_order是包括字符串:'32:5; 45:2; 555:23' 和等

我的問題:我確定有最好的解決方案來實現結果。任何人都可以幫我尋找解決方案嗎?請分享鏈接閱讀如何改進代碼

Tnx!

UPD:我需要總結的所有商品

+2

'customer_order'是字典嗎? 'dict'沒有'split'方法....你在做什麼 - 你用文字而不是代碼來描述它? – 2015-02-05 23:15:15

+0

'Goods.objects.'應該做什麼? – Marcin 2015-02-05 23:26:15

+1

@Marcin'Goods'是一個django模型。 'objects.filter'是一個數據庫查詢,它返回該模型中所有在該過濾器後面的對象(在這種情況下,'id in ids AND kind_cost == 1') – 2015-02-05 23:31:29

回答

0

看起來成本像customer_order是一個字符串,它看起來像一個字典(可能是JSON?)如果是JSON你應該使用json模塊解析它,但我會繼續工作,假設它實際上是一個本地Python字典對象作爲一個字符串。

import ast 

customer_order = ast.literal_eval(customer_order) 
# makes this into an ACTUAL dict... 

mList = Goods.objects.filter(id__in=customer_order.keys(), 
           kind_cost=1).values('id', 'cost') 
# mList is now a list of dicts, each dict has keys `id` and `cost` 

mList = dict([k.values() for k in mList]) 
# mList is now a single dict with id:cost pairings 

# As a lengthy aside, you might be better off just doing: 
# 
# # mList = Goods.objects.filter(id__in=customer_order.keys(),kind_cost=1) 
# # mList = {item.id:item.cost for item in mList} 
# 
# I find that must easier to read. If your items have a huge number of 
# columns, of course, this will vastly increase your query time. YMMV. 

result = [qty * mList[id] for id,qty in customer_order.items()] 

如果customer_order實際上只是鍵值配對,看起來像key1:value1;key2:value2那麼你就必須做一些預處理。

customer_order = {keyvalue.split(":") for keyvalue in customer_order.split(";")} 
+0

'customer_order'不是JSON它更類似於CommaSeparatedField,但使用分號。 – 2015-02-06 01:10:54