MCPcopy
hub / github.com/ormar-orm/ormar / _query_aggr_function

Method _query_aggr_function

ormar/queryset/queryset.py:803–824  ·  view source on GitHub ↗
(self, func_name: str, columns: list)

Source from the content-addressed store, hash-verified

801 return int(result) if result is not None else 0
802
803 async def _query_aggr_function(self, func_name: str, columns: list) -> Any:
804 func = getattr(sqlalchemy.func, func_name)
805 select_actions = [
806 SelectAction(select_str=column, model_cls=self.model) for column in columns
807 ]
808 if func_name in ["sum", "avg"]:
809 if any(not x.is_numeric for x in select_actions):
810 raise QueryDefinitionError(
811 "You can use sum and svg only with numeric types of columns"
812 )
813 if any(x.field_name not in x.target_model.model_fields for x in select_actions):
814 raise QueryDefinitionError(
815 "You can use aggregate functions only on "
816 "existing columns of the target model"
817 )
818 select_columns = [x.apply_func(func, use_label=True) for x in select_actions]
819 expr = self.build_select_expression().alias(f"subquery_for_{func_name}")
820 expr = sqlalchemy.select(*select_columns).select_from(expr) # type: ignore
821 # print("\n", expr.compile(compile_kwargs={"literal_binds": True}))
822 async with self.model_config.database.get_query_executor() as executor:
823 result = await executor.fetch_one(expr) # type: ignore
824 return dict(result) if len(result) > 1 else result[columns[0]] # type: ignore
825
826 async def max(self, columns: Union[str, list[str]]) -> Any: # noqa: A003
827 """

Callers 4

maxMethod · 0.95
minMethod · 0.95
sumMethod · 0.95
avgMethod · 0.95

Calls 6

SelectActionClass · 0.90
apply_funcMethod · 0.80
get_query_executorMethod · 0.80
fetch_oneMethod · 0.80

Tested by

no test coverage detected