2015-02-05 68 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