Add get_object_cached_field() for fetching cached object field values.
Review Request #14326 — Created Feb. 4, 2025 and updated
When working with a queryset involving
select_related()
or
prefetch_related()
, it's often useful to be able to check for and
access data returned from the corresponding caches, without the risk of
triggering an unwanted lookup. We use this to conditionally access state
or perform a new query, depending on its presence.To simplify this pattern, this change introduces
get_object_cached_field()
, which returns cached state for a field or
relation on an object.It first looks up in the field cache (which is populated by
select_related()
and may also be populated by a field's implementation
manually).If not found there, it then checks the
prefetch_related()
cache.If still not found, it returns
UNSET
.
Unit tests pass.
Made use of this in in-progress work.
- Change Summary:
-
- Added safer prefetch cache key logic.
- Added assertions in the unit tests to sanity-check our relation classes.
- Commits:
-
Summary ID 4e7a65ed9bf2da9ed65369836dd567352f01ff1e 183a279e9b421dfa211b04b2354e65dcaf20ceaa - Diff:
-
Revision 2 (+564 -4)
Checks run (2 succeeded)
- Change Summary:
-
Fixed a typo in a comment.
- Commits:
-
Summary ID 183a279e9b421dfa211b04b2354e65dcaf20ceaa fddb1307921c4d0e395937b0fded933f691eebe8 - Diff:
-
Revision 3 (+564 -4)