Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/280.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何减少Django应用程序的查询量?_Python_Django - Fatal编程技术网

Python 如何减少Django应用程序的查询量?

Python 如何减少Django应用程序的查询量?,python,django,Python,Django,我的应用程序目前正在进行1000多个SQL查询,加载页面大约需要20秒。我似乎找不到一种方法来想出一个解决方案,以便更快地将相同的数据显示在模板中的表上。我不想显示100个结果,所以我的分页设置为100 这些是my my models.py中用于获取订单数量和总数的方法,这两种方法在my Company模型中,而get_order_计数也在我的联系人模型中 def get_order_count(self): orders = 0 for order in self.orders

我的应用程序目前正在进行1000多个SQL查询,加载页面大约需要20秒。我似乎找不到一种方法来想出一个解决方案,以便更快地将相同的数据显示在模板中的表上。我不想显示100个结果,所以我的分页设置为100

这些是my my models.py中用于获取订单数量和总数的方法,这两种方法在my Company模型中,而get_order_计数也在我的联系人模型中

def get_order_count(self):
    orders = 0
    for order in self.orders.all():
        orders += 1
    return orders

def get_order_sum(self):
    total_sum = 0
    for contact in self.contacts.all():
        for order in contact.orders.all():
            total_sum += order.total
    return total_sum
views.py 样板
你的两种方法效率很低。您可以将它们替换为注释,这些注释在数据库中的一个查询中计算所有内容。您尚未展示您的模型,但可能会出现以下情况:

class IndexView(ListView):
    template_name = "mailer/index.html"
    model = Company.objects.annotate(order_count=Count('orders')).annotate(order_sum=Sum('contacts__orders__total'))
    paginate_by = 100
现在您可以访问{company.order\u count}和{{company.order\u sum}

{% for company in company_list %}
    <tr id="company-row">
        <th id="company-name" scope="row">{{ company.name }}</th>
        <td>{{ company.get_order_count }}</td>
        <td id="order-sum">{{ company.get_order_sum|floatformat:2 }}</td>
        <td class="text-center">
           <input type="checkbox" name="select{{company.pk}}" id="">
       </td>
    </tr>
    {% for contact in company.contacts.all %}
        <tr id="contact-row">
            <th scope="row">&nbsp;</th>
            <td>{{ contact.first_name }} {{ contact.last_name }}</td>
            <td id="contact-orders">
                Orders: {{ contact.get_order_count }} 
            </td>
            <td></td>
        </tr>
    {% endfor %}
{% endfor %}
class IndexView(ListView):
    template_name = "mailer/index.html"
    model = Company.objects.annotate(order_count=Count('orders')).annotate(order_sum=Sum('contacts__orders__total'))
    paginate_by = 100