1

我的代码存在性能问题。我对 Python 有点陌生,我想不出更好的方法来执行以下代码。

我有一个外部数据库,其中有一个名为“cdr”的表,它不是 django 项目的一部分,我需要对这些行进行一些计算。为了获得我的变量值,我正在对我的 cdr 表中的每一行进行查询,这使我的代码非常慢。

这是我在 view.py 中的课程

def cdr_adm(request):
        cursor = connections['cdr'].cursor()
        cursor.execute("SELECT calldate, dst, billsec, accountcode, disposition, userfield FROM cdr where calldate >= '%s' and calldate < '%s' and disposition like '%s' and accountcode like '%s' and dst like '%s' and userfield like '%s'" %(start_date, end_date, status, customer, destino, provider))
        result = cursor.fetchall()
        time = 0
        price = 0
        price_prov = 0
        count = 0
        time_now = 0
        ANS = 0
        asr = 0
        rate_cust = 0
        rate_prov = 0

        for call in result:
                if call[3]:
                        #These 2 lines are the problem - It's very slow to run for all rows.
                        rate_cust = User.objects.get(username = call[3])
                        rate_prov = Provider.objects.get(name = call[5])
                        time_now = call[2] / 60
                        time =  time + time_now
                        count = count + 1
                        price = price + (float(rate_cust.first_name) * time_now)
                        price_prov = price_prov + (float(rate_prov.rate) * time_now)
                        if call[4] == "ANSWERED":
                                ANS = ANS + 1
        time = float(time)
        lucro = price - price_prov
        lucro = float(lucro)
        if count > 0:
                asr = (ANS / count)  * 100
        return render_to_response("cdr_all.html",
                {'calls':result,'price':price,'time':time,'count':count,'customers':customers, 'providers':providers,'price_prov':price_prov, 'lucro':lucro, 'asr':asr }, context_instance=RequestContext(request))

我正在考虑创建一个字典并在其中搜索,但我也不确定。

4

1 回答 1

2

您可以创建一个包含所有对象的字典,User并按Provider您感兴趣的内容进行索引,如下所示:

users = dict([(u.username, u) for u in User.objects.all()])
providers = dict([(p.name, p) for p in Provider.objects.all()])

(确保您在for call in result:for 循环之外执行此操作!)然后您可以将慢查询更改为:

                    rate_cust = users[call[3]]
                    rate_prov = provided[call[5]]

我猜用户和提供者的数量比调用少得多,这意味着将它们保存在字典中比为每次调用进行一次查询访问要快得多。

于 2012-09-08T05:19:39.927 回答