(self, args, kwargs, select=True)
| 1826 | return self._annotate(args, kwargs, select=False) |
| 1827 | |
| 1828 | def _annotate(self, args, kwargs, select=True): |
| 1829 | self._validate_values_are_expressions( |
| 1830 | args + tuple(kwargs.values()), method_name="annotate" |
| 1831 | ) |
| 1832 | annotations = {} |
| 1833 | for arg in args: |
| 1834 | # The default_alias property raises TypeError if default_alias |
| 1835 | # can't be set automatically or AttributeError if it isn't an |
| 1836 | # attribute. |
| 1837 | try: |
| 1838 | if arg.default_alias in kwargs: |
| 1839 | raise ValueError( |
| 1840 | "The named annotation '%s' conflicts with the " |
| 1841 | "default name for another annotation." % arg.default_alias |
| 1842 | ) |
| 1843 | except (TypeError, AttributeError): |
| 1844 | raise TypeError("Complex annotations require an alias") |
| 1845 | annotations[arg.default_alias] = arg |
| 1846 | annotations.update(kwargs) |
| 1847 | |
| 1848 | clone = self._chain() |
| 1849 | names = self._fields |
| 1850 | if names is None: |
| 1851 | names = set( |
| 1852 | chain.from_iterable( |
| 1853 | ( |
| 1854 | (field.name, field.attname) |
| 1855 | if hasattr(field, "attname") |
| 1856 | else (field.name,) |
| 1857 | ) |
| 1858 | for field in self.model._meta.get_fields() |
| 1859 | ) |
| 1860 | ) |
| 1861 | |
| 1862 | for alias, annotation in annotations.items(): |
| 1863 | if alias in names: |
| 1864 | raise ValueError( |
| 1865 | "The annotation '%s' conflicts with a field on " |
| 1866 | "the model." % alias |
| 1867 | ) |
| 1868 | if isinstance(annotation, FilteredRelation): |
| 1869 | clone.query.add_filtered_relation(annotation, alias) |
| 1870 | else: |
| 1871 | clone.query.add_annotation( |
| 1872 | annotation, |
| 1873 | alias, |
| 1874 | select=select, |
| 1875 | ) |
| 1876 | for alias, annotation in clone.query.annotations.items(): |
| 1877 | if alias in annotations and annotation.contains_aggregate: |
| 1878 | if clone._fields is None: |
| 1879 | clone.query.group_by = True |
| 1880 | else: |
| 1881 | clone.query.set_group_by() |
| 1882 | break |
| 1883 | |
| 1884 | return clone |
| 1885 |
no test coverage detected