MCPcopy
hub / github.com/django/django / as_sql

Method as_sql

django/db/models/aggregates.py:174–213  ·  view source on GitHub ↗
(self, compiler, connection, **extra_context)

Source from the content-addressed store, hash-verified

172 return []
173
174 def as_sql(self, compiler, connection, **extra_context):
175 if (
176 self.distinct
177 and not connection.features.supports_aggregate_distinct_multiple_argument
178 and len(super().get_source_expressions()) > 1
179 ):
180 raise NotSupportedError(
181 f"{self.name} does not support distinct with multiple expressions on "
182 f"this database backend."
183 )
184
185 distinct_sql = "DISTINCT " if self.distinct else ""
186 order_by_sql = ""
187 order_by_params = []
188 filter_sql = ""
189 filter_params = []
190
191 if (order_by := self.order_by) is not None:
192 order_by_sql, order_by_params = compiler.compile(order_by)
193
194 if self.filter is not None:
195 try:
196 filter_sql, filter_params = compiler.compile(self.filter)
197 except NotSupportedError:
198 # Fallback to a CASE statement on backends that don't support
199 # the FILTER clause.
200 copy = self.copy()
201 copy.filter = None
202 source_expressions = copy.get_source_expressions()
203 condition = When(self.filter.condition, then=source_expressions[0])
204 copy.set_source_expressions([Case(condition)] + source_expressions[1:])
205 return copy.as_sql(compiler, connection, **extra_context)
206
207 extra_context.update(
208 distinct=distinct_sql,
209 filter=filter_sql,
210 order_by=order_by_sql,
211 )
212 sql, params = super().as_sql(compiler, connection, **extra_context)
213 return sql, (*params, *order_by_params, *filter_params)
214
215 def _get_repr_options(self):
216 options = super()._get_repr_options()

Callers

nothing calls this directly

Calls 9

NotSupportedErrorClass · 0.90
WhenClass · 0.90
CaseClass · 0.90
compileMethod · 0.45
copyMethod · 0.45
as_sqlMethod · 0.45
updateMethod · 0.45

Tested by

no test coverage detected