Expand the GROUP BY clause required by the query. This will usually be the set of all non-aggregate fields in the return data. If the database backend supports grouping by the primary key, and the query would be equivalent, the optimization will be made auto
(self, allow_aliases=True)
| 2409 | query.clear_ordering(force=False, clear_default=clear_default) |
| 2410 | |
| 2411 | def set_group_by(self, allow_aliases=True): |
| 2412 | """ |
| 2413 | Expand the GROUP BY clause required by the query. |
| 2414 | |
| 2415 | This will usually be the set of all non-aggregate fields in the |
| 2416 | return data. If the database backend supports grouping by the |
| 2417 | primary key, and the query would be equivalent, the optimization |
| 2418 | will be made automatically. |
| 2419 | """ |
| 2420 | if allow_aliases and self.values_select: |
| 2421 | # If grouping by aliases is allowed assign selected value aliases |
| 2422 | # by moving them to annotations. |
| 2423 | group_by_annotations = {} |
| 2424 | values_select = {} |
| 2425 | for alias, expr in zip(self.values_select, self.select): |
| 2426 | if isinstance(expr, Col): |
| 2427 | values_select[alias] = expr |
| 2428 | else: |
| 2429 | group_by_annotations[alias] = expr |
| 2430 | self.annotations = {**group_by_annotations, **self.annotations} |
| 2431 | self.append_annotation_mask(group_by_annotations) |
| 2432 | self.select = tuple(values_select.values()) |
| 2433 | self.values_select = tuple(values_select) |
| 2434 | if self.selected is not None: |
| 2435 | for index, value_select in enumerate(values_select): |
| 2436 | self.selected[value_select] = index |
| 2437 | group_by = list(self.select) |
| 2438 | for alias, annotation in self.annotation_select.items(): |
| 2439 | if not (group_by_cols := annotation.get_group_by_cols()): |
| 2440 | continue |
| 2441 | if allow_aliases and not annotation.contains_aggregate: |
| 2442 | group_by.append(Ref(alias, annotation)) |
| 2443 | else: |
| 2444 | group_by.extend(group_by_cols) |
| 2445 | self.group_by = tuple(group_by) |
| 2446 | |
| 2447 | def add_select_related(self, fields): |
| 2448 | """ |
no test coverage detected