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