0

我期待 postgres 需要一些时间,但没想到它不会成为这里的瓶颈,我该如何解决这个问题?

2772856 function calls (2578490 primitive calls) in 32.361 seconds

Ordered by: internal time

ncalls  tottime  percall  cumtime  percall filename:lineno(function)
127921/19340    3.670    0.000   11.486    0.001 /usr/lib/python2.7/copy.py:145(deepcopy)
 2240    3.031    0.001    3.244    0.001 {method 'execute' of 'psycopg2._psycopg.cursor' objects}
114402    1.541    0.000    2.348    0.000 /usr/lib/python2.7/copy.py:267(_keep_alive)

-------------------------------------------------- --------------------------------

    suppliers = models.Supplier.objects.all().order_by('company')
    for supplier in suppliers :
        sup = {}
        sup['company'] = supplier.company
        sup['supplies'] = get_supplies(1, supplier.uuid)
        sup['category'] = 'Supplier'
        if isocode == None :
            addresses = models.Address.objects.filter(company = supplier.company)
        else :
            addresses = models.Address.objects.filter(company = supplier.company, country_iso = isocode)
        sup['contacts'] = models.Contact.objects.filter(address__in=addresses)
        company_list.append(sup)

-------------------------------------------------- --------------------------------

def get_supplies (bought_in_controlpanel_id, supplier_uuid) :

    supplier    = None
    activenode  = None

    if supplier_uuid is not None :
        supplier = models.Supplier.objects.get(uuid = supplier_uuid)

    try :
        activenode = boughtin.BoughtInControlPanel.objects.get (pk = 1)
    except :
        pass

    supplies = boughtin.BoughtInControlPanel.objects.filter (parent = activenode)
    for supply in supplies :
        supply.checked  = 0
        supply.disabled = ""
        supply.open     = 0

        if supplier_uuid is not None :
            try    :
                models.Supplies.objects.get(supplier = supplier, bought_in_control_panel = supply)
                supply.checked = 1
            except :
                supply.open    = 1

    return supplies
4

1 回答 1

3

当您在循环中查询数据库时,性能通常很差。尽量避免这种情况。

为什么不继续使用关系和__in查询?=)

我认为这应该适用于第一个示例的 SQL 查询较少:

company_list = models.Supplier.objects.values_list('company', flat=True)

filter_kwargs = dict(address__company__in=company_list)

if isocode is not None:
    filter_kwargs.update(dict(address__company__isocode=isocode))

sup['contacts'] = models.Contact.objects.filter(**filter_kwargs)

关于get_supplies(),我也会避免Supplies.objects.get()循环,除非你确定它只会被击中几次。最好在循环之前用一个更大的查询收集一个供应列表,然后简单地检查该列表中是否存在所需的项目。尽管您应该分析这两种变体并选择更快的一种。

于 2012-07-09T12:10:36.787 回答