MCPcopy
hub / github.com/django/django / _annotate

Method _annotate

django/db/models/query.py:1828–1884  ·  view source on GitHub ↗
(self, args, kwargs, select=True)

Source from the content-addressed store, hash-verified

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

Callers 2

annotateMethod · 0.95
aliasMethod · 0.95

Calls 9

_chainMethod · 0.95
add_filtered_relationMethod · 0.80
add_annotationMethod · 0.80
set_group_byMethod · 0.80
valuesMethod · 0.45
updateMethod · 0.45
get_fieldsMethod · 0.45
itemsMethod · 0.45

Tested by

no test coverage detected