【发布时间】:2021-09-13 14:20:23
【问题描述】:
我的目标是优化 Django 模型中对象计数的检索。
我有两个模型:
- 用户
- 前景
这是一对多的关系。一个用户可以创建多个前景。一个潜在客户只能由一个用户创建。
我正在尝试获取用户在过去 24 小时内创建的潜在客户。
Prospects 模型在我的 PostgreSQL 数据库中大约有 700 万行。用户只有 2000 个。
我当前的代码需要很长时间才能获得所需的结果。
我尝试使用filter() 和count():
import datetime
# get the date but 24 hours earlier
date_example = datetime.datetime.now() - datetime.timedelta(days = 1)
# Filter Prospects that are created by user_id_example
# and filter Prospects that got a date greater than date_example (so equal or sooner)
today_prospects = Prospect.objects.filter(user_id = 'user_id_example', create_date__gte = date_example)
# get the count of prospects that got created in the past 24 hours by user_id_example
# this is the problematic call that takes too long to process
count_total_today_prospects = today_prospects.count()
我在工作,但需要太多时间(5 分钟)。因为它检查的是整个数据库,而不仅仅是检查,我认为它会:只检查用户在过去 24 小时内创建的潜在客户。
我也尝试过使用 annotate,但它同样慢,因为它最终做的事情与普通的 .count() 相同:
today_prospects.annotate(Count('id'))
如何以更优化的方式获得计数?
【问题讨论】:
-
如果为
create_date字段添加db_index=True会怎样?添加后需要先迁移数据库。 -
目前我的字段是:
create_date = models.DateTimeField(auto_now = True)我应该把它改成create_date = models.DateTimeField(auto_now = True, db_index = True)然后呢?同样的.count方法应该工作得更快吗? @WillemVanOnsem -
@RobZ 不,您仍然需要使用适当的列索引更新您的数据库。
标签: python django postgresql