serializer_cache#
SerializerCacheBase#
Helper base class for using a cache backend during serialization.
Provides a dict-based short term cache that fetches its data from a Django cache backend and supports committing changes back.
For usage example, see SerializerCacheSerializer.
Source code in src/apps/cache/serializer_cache.py
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 |
|
fetch_from_source(instances, include_newer=False)
#
Fetch cached data from source cache.
Fetch cached values that match modification timestamp of corresponding instance.
Source code in src/apps/cache/serializer_cache.py
get_source_cache()
classmethod
#
set_value(instance, value, value_context=None, only_if_modified=False)
#
Set per-instance value to cache.
The in-memory value is not copied so care needs to be taken to avoid modifying it after using set_value.
Source code in src/apps/cache/serializer_cache.py
SerializerCacheSerializer#
Bases: Serializer
Serializer with support for partially cached field values.
Only fields in cached_fields are cached, so cache invalidation is needed only when a value in cached_fields changes.
Usage example:
class SerializerCache:
cache_name = "default" # Use default Django cache
cached_fields = {"field1", "field2"} # Which fields are cached
modified_attr = "modified" # Model field containing timestamp of latest modification
class SomeSerializer(ModelSerializer, SerializerCacheSerializer):
...
def to_representation(self, instance):
ret = super().to_representation(instance)
if cache := get_serializer_cache():
# Save serialized value to serializer cache
cache.set_value(instance, ret, only_if_modified=True)
return ret
# Serialize instances using cached values
instances = SomeModel.objects.filter(...)
cache = SerializerCache(instances)
serializer = SomeSerializer(instances, cache=cache, many=True)
serialized_values = serializer.data
Source code in src/apps/cache/serializer_cache.py
117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 |
|
get_cached_field_sources()
#
List sources of cached fields.
Source code in src/apps/cache/serializer_cache.py
to_representation(instance)
#
Serialization modified to support cached values.