| 215 | def test_cache_read_for_model_instance(self): |
| 216 | # Don't want fields with callable as default to be called on cache read |
| 217 | expensive_calculation.num_runs = 0 |
| 218 | Poll.objects.all().delete() |
| 219 | my_poll = Poll.objects.create(question="Well?") |
| 220 | self.assertEqual(Poll.objects.count(), 1) |
| 221 | pub_date = my_poll.pub_date |
| 222 | self.cache.set('question', my_poll) |
| 223 | cached_poll = self.cache.get('question') |
| 224 | self.assertEqual(cached_poll.pub_date, pub_date) |
| 225 | # We only want the default expensive calculation run once |
| 226 | self.assertEqual(expensive_calculation.num_runs, 1) |
| 227 | |
| 228 | def test_cache_write_for_model_instance_with_deferred(self): |
| 229 | # Don't want fields with callable as default to be called on cache write |
| 230 | expensive_calculation.num_runs = 0 |
| 231 | Poll.objects.all().delete() |
| 232 | my_poll = Poll.objects.create(question="What?") |
| 233 | self.assertEqual(expensive_calculation.num_runs, 1) |
| 234 | defer_qs = Poll.objects.all().defer('question') |
| 235 | self.assertEqual(defer_qs.count(), 1) |
| 236 | self.cache.set('deferred_queryset', defer_qs) |
| 237 | # cache set should not re-evaluate default functions |
| 238 | self.assertEqual(expensive_calculation.num_runs, 1) |
| 239 | |
| 240 | def test_cache_read_for_model_instance_with_deferred(self): |
| 241 | # Don't want fields with callable as default to be called on cache read |
| 242 | expensive_calculation.num_runs = 0 |
| 243 | Poll.objects.all().delete() |
| 244 | my_poll = Poll.objects.create(question="What?") |
| 245 | self.assertEqual(expensive_calculation.num_runs, 1) |
| 246 | defer_qs = Poll.objects.all().defer('question') |
| 247 | self.assertEqual(defer_qs.count(), 1) |
| 248 | self.cache.set('deferred_queryset', defer_qs) |
| 249 | runs_before_cache_read = expensive_calculation.num_runs |
| 250 | cached_polls = self.cache.get('deferred_queryset') |
| 251 | # We only want the default expensive calculation run on creation and set |
| 252 | self.assertEqual(expensive_calculation.num_runs, runs_before_cache_read) |
| 253 | |