有效列出数据库对象

时间:2015-03-07 13:19:06

标签: python django database django-database

我正在一个列出公司及其员工的页面上工作。员工有销售。这些保存在数据库中。现在我需要列出所有这些。我的问题是目前的解决方案并不快。一页加载需要15秒。

目前我已做过以下事情:

companies = {}
employees = {}

for company in Company.objects.all():
    sales_count = 0
    sales_sum = 0

    companies[company.id] = {}
    companies[company.id]["name"] = company.name

    for employee in company.employees.all():
        employee_sales_count = 0
        employee_sales_sum = 0

        employees[employee.id] = {}
        employees[employee.id]["name"] = employee.first_name + " " + employee.last_name

        for sale in employee.sales.all():
            employee_sales_count+= 1
            employee_sales_sum += sale.total

        employees[employee.id]["sales_count"] = employee_sales_count
        employees[employee.id]["sales_sum"] = employee_sales_sum

        sales_count += employee_sales_count
        sales_sum += employee_sales_sum

    companies[company.id]["sales_count"] = sales_count
    companies[company.id]["sales_sum"] = sales_sum

我是Python新手,不确定这是否是" pythonic"做事的方式。

这使得对数据库的1500次查询包含100家公司,一些员工和销售人员。我应该如何改进我的计划以提高效率?

1 个答案:

答案 0 :(得分:0)

避免在循环中嵌套数据库查询 - 这是一个很好的表现地狱的方法! : - )

由于您计算所有员工的所有销售额,我建议您自己构建员工和销售人员。不要忘记导入defaultdict,你可能想要查询分组和总结/计数在Django中是如何工作的: - )

让我们看看......这应该可以告诉你从哪里开始:

# build employee dict
employee_qset = Employee.objects.all()
employees = defaultdict(dict)
for emp in employee_qset.iterator():
    employees[emp.company_id][emp.id] = emp


# build sales dict
sales_qset = Sales.objects.all()
sales = defaultdict(dict)
for sale in sales_qset.iterator():
    # you could do some calculations here, like sum, or better yet do sums via annotate and group_by in the database
    sales[sale.employee_id][sale.id] = sale


# get companies
companies_qset = Companies.objects.all()
companies = {company.id: company for company in companies_qset.iterator()}


for company in companies.itervalues():
    # assign employees, assign sales, etc.
    pass