9 examples of 'django group by' in Python

Every line of 'django group by' code snippets is scanned for vulnerabilities by our powerful machine learning engine that combs millions of open source libraries, ensuring your Python code is secure.

All examples are scanned by Snyk Code

By copying the Snyk Code Snippets you agree to
this disclaimer
2757@typecheck(f=func_spec(1, expr_any),
2758 collection=expr_oneof(expr_set(), expr_array()))
2759def group_by(f: Callable, collection) -> DictExpression:
2760 """Group collection elements into a dict according to a lambda function.
2761
2762 Examples
2763 --------
2764
2765 >>> a = ['The', 'quick', 'brown', 'fox']
2766
2767 >>> hl.eval(hl.group_by(lambda x: hl.len(x), a))
2768 {5: ['quick', 'brown'], 3: ['The', 'fox']}
2769
2770 Parameters
2771 ----------
2772 f : function ( (arg) -> :class:`.Expression`)
2773 Function to evaluate for each element of the collection to produce a key for the
2774 resulting dictionary.
2775 collection : :class:`.ArrayExpression` or :class:`.SetExpression`
2776 Collection expression.
2777
2778 Returns
2779 -------
2780 :class:`.DictExpression`.
2781 Dictionary keyed by results of `f`.
2782 """
2783 return collection.group_by(f)
Important

Use secure code every time

Secure your code as it's written. Use Snyk Code to scan source code in minutes – no build needed – and fix issues immediately. Enable Snyk Code

85def group_by(self, *fields):
86 return self._clone(group_by=fields)
376def group_by(collection, iteratee=None):
377 """Creates an object composed of keys generated from the results of running
378 each element of a `collection` through the iteratee.
379
380 Args:
381 collection (list|dict): Collection to iterate over.
382 iteratee (mixed, optional): Iteratee applied per iteration.
383
384 Returns:
385 dict: Results of grouping by `iteratee`.
386
387 Example:
388
389 >>> results = group_by([{'a': 1, 'b': 2}, {'a': 3, 'b': 4}], 'a')
390 >>> assert results == {1: [{'a': 1, 'b': 2}], 3: [{'a': 3, 'b': 4}]}
391 >>> results = group_by([{'a': 1, 'b': 2}, {'a': 3, 'b': 4}], {'a': 1})
392 >>> assert results == {False: [{'a': 3, 'b': 4}],\
393 True: [{'a': 1, 'b': 2}]}
394
395 .. versionadded:: 1.0.0
396 """
397 ret = {}
398 cbk = pyd.iteratee(iteratee)
399
400 for value in collection:
401 key = cbk(value)
402 ret.setdefault(key, [])
403 ret[key].append(value)
404
405 return ret
138def order_by(self, *args):
139 """
140 Order of concatination.
141
142 .. code-block:: python
143
144 >>> sqlpuzzle.group_concat('col').order_by('col')
145 <GroupConcat: GROUP_CONCAT("col" ORDER BY "col")>
146 """
147 self._order_by.order_by(*args)
148 return self
155def get_group_by_cols(self):
156 cols = []
157 for child in self.children:
158 if hasattr(child, 'get_group_by_cols'):
159 cols.extend(child.get_group_by_cols())
160 else:
161 if isinstance(child[0], Constraint):
162 cols.append((child[0].alias, child[0].col))
163 if hasattr(child[3], 'get_group_by_cols'):
164 cols.extend(child[3].get_group_by_cols())
165 return cols
23def _group_by(self):
24 group_by_str = super(AccountInvoiceReport, self)._group_by()
25 group_by_str += ", ai.number"
26 return group_by_str
1109def test_fobj_group_by(self):
1110 """
1111 Check that an F() object referring to related column works correctly
1112 in group by.
1113 """
1114 qs = Book.objects.annotate(
1115 acount=Count('authors')
1116 ).filter(
1117 acount=F('publisher__num_awards')
1118 )
1119 self.assertQuerysetEqual(
1120 qs, ['Sams Teach Yourself Django in 24 Hours'],
1121 lambda b: b.name)
739def _get_group_by_cols(*args): # pragma: no cover
740 return []
128def group_by(self, dataset, field_name=None):
129 if field_name is None:
130 field_name = self.field_name
131
132 items = self._get_base_set(dataset)
133
134 # Get the min and max
135 min_val, max_val = self._get_range(items, field_name)
136 if min_val is None:
137 return []
138
139 # Get a good bin size
140 bin_size = self._get_bin_size(min_val, max_val)
141
142 # Calculate a grouping variable
143 items = self._add_grouping_value(items, bin_size, field_name)
144
145 # Group by it
146 items = items.values('value')
147
148 # Count the messages in each group
149 result = self._annotate(items)
150
151 return BinnedResultSet(result, bin_size, min_val, max_val)

Related snippets