为什么Django相关的对象查询没有被缓存?

问题描述 投票:0回答:1

我有以下单元测试:

def test_cache(self):
    with self.assertNumQueries(1):
        print(database.records.all())
        print(database.records.all())
        print(database.records.all())

测试失败,因为进行了 3 次查询:

Captured queries were:
1. SELECT "store_record"."id", "store_record"."key", "store_record"."database_id", "store_record"."user_id", "store_record"."organization_id", "store_record"."data", "store_record"."created_at", "store_record"."updated_at" FROM "store_record" WHERE "store_record"."database_id" = '7d86d143-9e4e-4420-801c-3d3c5e6875fb'::uuid LIMIT 21
2. SELECT "store_record"."id", "store_record"."key", "store_record"."database_id", "store_record"."user_id", "store_record"."organization_id", "store_record"."data", "store_record"."created_at", "store_record"."updated_at" FROM "store_record" WHERE "store_record"."database_id" = '7d86d143-9e4e-4420-801c-3d3c5e6875fb'::uuid LIMIT 21
3. SELECT "store_record"."id", "store_record"."key", "store_record"."database_id", "store_record"."user_id", "store_record"."organization_id", "store_record"."data", "store_record"."created_at", "store_record"."updated_at" FROM "store_record" WHERE "store_record"."database_id" = '7d86d143-9e4e-4420-801c-3d3c5e6875fb'::uuid LIMIT 21

为什么记录字段没有被缓存?什么告诉 Django 从数据库中重新获取数据?

django django-orm
1个回答
0
投票

记录

除了缓存整个查询集之外,还有缓存 ORM 对象属性的结果。一般来说,属性是 不可调用的将被缓存。例如,假设示例博客 型号:

 entry = Entry.objects.get(id=1)
 entry.blog  # Blog object is retrieved at this point
 entry.blog  # cached version, no DB access   But in general, callable attributes cause DB lookups every time:

 entry = Entry.objects.get(id=1)
 entry.authors.all()  # query performed
 entry.authors.all()  # query performed again

但这不是问题,因为如果您需要访问作者(在您的情况下为 store_records),您将正确使用

prefetch_related

© www.soinside.com 2019 - 2024. All rights reserved.