data.py 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  1. import warnings
  2. from django.utils.functional import cached_property
  3. from .utils import OrderBy, OrderByTuple, segment
  4. class TableData:
  5. """
  6. Base class for table data containers.
  7. """
  8. def __init__(self, data):
  9. self.data = data
  10. def __getitem__(self, key):
  11. """
  12. Slicing returns a new `.TableData` instance, indexing returns a single record.
  13. """
  14. return self.data[key]
  15. def __iter__(self):
  16. """
  17. for ... in ... default to using this. There's a bug in Django 1.3
  18. with indexing into QuerySets, so this side-steps that problem (as well
  19. as just being a better way to iterate).
  20. """
  21. return iter(self.data)
  22. def set_table(self, table):
  23. """
  24. `Table.__init__` calls this method to inject an instance of itself into the
  25. `TableData` instance.
  26. Good place to do additional checks if Table and TableData instance will work
  27. together properly.
  28. """
  29. self.table = table
  30. @property
  31. def model(self):
  32. return getattr(self.data, "model", None)
  33. @property
  34. def ordering(self):
  35. return None
  36. @property
  37. def verbose_name(self):
  38. return "item"
  39. @property
  40. def verbose_name_plural(self):
  41. return "items"
  42. @staticmethod
  43. def from_data(data):
  44. # allow explicit child classes of TableData to be passed to Table()
  45. if isinstance(data, TableData):
  46. return data
  47. if TableQuerysetData.validate(data):
  48. return TableQuerysetData(data)
  49. elif TableListData.validate(data):
  50. return TableListData(list(data))
  51. raise ValueError(
  52. "data must be QuerySet-like (have count() and order_by()) or support"
  53. " list(data) -- {} has neither".format(type(data).__name__)
  54. )
  55. class TableListData(TableData):
  56. """
  57. Table data container for a list of dicts, for example::
  58. [
  59. {'name': 'John', 'age': 20},
  60. {'name': 'Brian', 'age': 25}
  61. ]
  62. .. note::
  63. Other structures might have worked in the past, but are not explicitly
  64. supported or tested.
  65. """
  66. @staticmethod
  67. def validate(data):
  68. """
  69. Validates `data` for use in this container
  70. """
  71. return hasattr(data, "__iter__") or (
  72. hasattr(data, "__len__") and hasattr(data, "__getitem__")
  73. )
  74. def __len__(self):
  75. return len(self.data)
  76. @property
  77. def verbose_name(self):
  78. return getattr(self.data, "verbose_name", super().verbose_name)
  79. @property
  80. def verbose_name_plural(self):
  81. return getattr(self.data, "verbose_name_plural", super().verbose_name_plural)
  82. def order_by(self, aliases):
  83. """
  84. Order the data based on order by aliases (prefixed column names) in the
  85. table.
  86. Arguments:
  87. aliases (`~.utils.OrderByTuple`): optionally prefixed names of
  88. columns ('-' indicates descending order) in order of
  89. significance with regard to data ordering.
  90. """
  91. accessors = []
  92. for alias in aliases:
  93. bound_column = self.table.columns[OrderBy(alias).bare]
  94. # bound_column.order_by reflects the current ordering applied to
  95. # the table. As such we need to check the current ordering on the
  96. # column and use the opposite if it doesn't match the alias prefix.
  97. if alias[0] != bound_column.order_by_alias[0]:
  98. accessors += bound_column.order_by.opposite
  99. else:
  100. accessors += bound_column.order_by
  101. self.data.sort(key=OrderByTuple(accessors).key)
  102. class TableQuerysetData(TableData):
  103. """
  104. Table data container for a queryset.
  105. """
  106. @staticmethod
  107. def validate(data):
  108. """
  109. Validates `data` for use in this container
  110. """
  111. return (
  112. hasattr(data, "count")
  113. and callable(data.count)
  114. and hasattr(data, "order_by")
  115. and callable(data.order_by)
  116. )
  117. def __len__(self):
  118. """Cached data length"""
  119. if not hasattr(self, "_length") or self._length is None:
  120. if hasattr(self.table, "paginator"):
  121. # for paginated tables, use QuerySet.count() as we are interested in total number of records.
  122. self._length = self.data.count()
  123. else:
  124. # for non-paginated tables, use the length of the QuerySet
  125. self._length = len(self.data)
  126. return self._length
  127. def set_table(self, table):
  128. super().set_table(table)
  129. if self.model and getattr(table._meta, "model", None) and self.model != table._meta.model:
  130. warnings.warn(
  131. "Table data is of type {} but {} is specified in Table.Meta.model".format(
  132. self.model, table._meta.model
  133. )
  134. )
  135. @property
  136. def ordering(self):
  137. """
  138. Returns the list of order by aliases that are enforcing ordering on the
  139. data.
  140. If the data is unordered, an empty sequence is returned. If the
  141. ordering can not be determined, `None` is returned.
  142. This works by inspecting the actual underlying data. As such it's only
  143. supported for querysets.
  144. """
  145. aliases = {}
  146. for bound_column in self.table.columns:
  147. aliases[bound_column.order_by_alias] = bound_column.order_by
  148. try:
  149. return next(segment(self.data.query.order_by, aliases))
  150. except StopIteration:
  151. pass
  152. def order_by(self, aliases):
  153. """
  154. Order the data based on order by aliases (prefixed column names) in the
  155. table.
  156. Arguments:
  157. aliases (`~.utils.OrderByTuple`): optionally prefixed names of
  158. columns ('-' indicates descending order) in order of
  159. significance with regard to data ordering.
  160. """
  161. modified_any = False
  162. accessors = []
  163. for alias in aliases:
  164. bound_column = self.table.columns[OrderBy(alias).bare]
  165. # bound_column.order_by reflects the current ordering applied to
  166. # the table. As such we need to check the current ordering on the
  167. # column and use the opposite if it doesn't match the alias prefix.
  168. if alias[0] != bound_column.order_by_alias[0]:
  169. accessors += bound_column.order_by.opposite
  170. else:
  171. accessors += bound_column.order_by
  172. if bound_column:
  173. queryset, modified = bound_column.order(self.data, alias[0] == "-")
  174. if modified:
  175. self.data = queryset
  176. modified_any = True
  177. # custom ordering
  178. if modified_any:
  179. return
  180. # Traditional ordering
  181. if accessors:
  182. order_by_accessors = (a.for_queryset() for a in accessors)
  183. self.data = self.data.order_by(*order_by_accessors)
  184. @cached_property
  185. def verbose_name(self):
  186. """
  187. The full (singular) name for the data.
  188. Model's `~django.db.Model.Meta.verbose_name` is honored.
  189. """
  190. return self.data.model._meta.verbose_name
  191. @cached_property
  192. def verbose_name_plural(self):
  193. """
  194. The full (plural) name for the data.
  195. Model's `~django.db.Model.Meta.verbose_name` is honored.
  196. """
  197. return self.data.model._meta.verbose_name_plural