优化 Django 中的计数查询

Optimize count query in Django

我有以下疑问:

files = DataAvailability.objects.all()
type1 = files.filter(type1=True)
type2 = files.filter(type2=True)

# People information
people = Person.objects.all()
users = people.filter(is_subject=True)

# count information (this is taking a long time to query them all)
type1_users = type1.filter(person__in=users).count()
type2_users = type2.filter(person__in=users).count()
total_users = files.filter(person__in=users).count()
# another way
total_users2 = files.filter(person__in=users)
type1_users2 = total_users.filter(type1=True).count()
type2_users2 = total_users.filter(type2=True).count()
total_count = total_users2.count()

我考虑过使用 .values() 创建一个查询并放入 set()。 完成后执行集合中的一些函数(如 diff)。

这是缩短查询时间的唯一方法吗?

我不必经常进行这些查询(最多一天一次)。所以我正在 运行 执行将数据导出到文件的 cron 作业(您可以在数据库中创建一个 table 用于审计目的,例如)。然后我读取文件并使用那里的数据。正在运行 well/fast。

你总是可以生吃 SQL https://docs.djangoproject.com/en/2.0/topics/db/sql/#performing-raw-queries

示例:

# Dont do this its insecure
YourModel.objects.raw(f"select id from {YourModel._meta.db_table}") 

# Do like this to avoid SQL injection issues.
YourModel.objects.raw("select id from app_model_name") 

table 的名称可以通过以下方式获得:YourModel._meta.db_table 也可以像这样获得查询集的 sql:

type1_users = type1.filter(person__in=users)
type1_users.query.__str__()

因此您可以将此查询连接到另一个查询。