我的目标是优化在Django模型中对象数量的检索。
我有两个模型:
- 用户
- 潜在客户
这是一种一对多的关系。一个用户可以创建多个潜在客户,而一个潜在客户只能由一个用户创建。
我试图获取用户在过去的24小时内创建的潜在客户。
在我的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 = models.DateTimeField(auto_now = True)
我应该将其改为create_date = models.DateTimeField(auto_now = True, db_index = True)
然后呢?同样的.count
方法会更快吗?@WillemVanOnsem - RobZ