Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

1import logging 

2from typing import Optional, TYPE_CHECKING, Any, Sequence 

3 

4logger = logging.getLogger(__name__) 

5 

6 

7class CachedFieldsMixin: 

8 """ 

9 Cached fields mixin. Usage: 

10 1) List cached field names in cached_fields list 

11 2) Implement get_xxx functions where xxx is cached field name 

12 3) Call update_cached_fields() to refresh 

13 4) Optionally call update_cached_fields_pre_save() on pre_save signal for objects (to automatically refresh on save) 

14 """ 

15 

16 cached_fields: Sequence[str] = [] 

17 

18 if TYPE_CHECKING: 

19 pk: Any = None 

20 

21 def save(self, force_insert=False, force_update=False, using=None, update_fields=None): 

22 pass 

23 

24 def update_cached_fields( 

25 self, commit: bool = True, exceptions: bool = True, updated_fields: Optional[Sequence[str]] = None 

26 ): 

27 """ 

28 Updates cached fields using get_xxx calls for each cached field (in cached_fields list). 

29 :param commit: Save update fields to DB 

30 :param exceptions: Raise exceptions or not 

31 :param updated_fields: List of cached fields to update. Pass None for all cached fields. 

32 """ 

33 try: 

34 fields = updated_fields or self.cached_fields 

35 for k in fields: 

36 f = "get_" + k 

37 if not hasattr(self, f): 

38 raise Exception( 

39 "Field {k} marked as cached in {obj} but function get_{k}() does not exist".format( 

40 k=k, obj=self 

41 ) 

42 ) 

43 v = self.__getattribute__(f)() 

44 setattr(self, k, v) 

45 if commit: 

46 self.save(update_fields=fields) # pytype: disable=attribute-error 

47 except Exception as e: 

48 logger.error("%s.update_cached_fields: %s", self.__class__, e) 

49 if exceptions: 

50 raise e 

51 

52 def update_cached_fields_pre_save(self, update_fields: Optional[Sequence[str]]): 

53 """ 

54 Call on pre_save signal for objects (to automatically refresh on save). 

55 :param update_fields: list of fields to update 

56 """ 

57 if hasattr(self, "pk") and self.pk and update_fields is None: 

58 self.update_cached_fields(commit=False, exceptions=False) 

59 

60 

61def update_cached_fields(*args): 

62 """ 

63 Calls update_cached_fields() for each object passed in as argument. 

64 Supports also iterable objects by checking __iter__ attribute. 

65 :param args: List of objects 

66 :return: None 

67 """ 

68 for a in args: 

69 if a is not None: 

70 if hasattr(a, "__iter__"): 

71 for e in a: 

72 e.update_cached_fields() 

73 else: 

74 a.update_cached_fields()