Returns number of rows matching the given criteria (applied with `filter` and `exclude` if set before). If `distinct` is `True` (the default), this will return the number of primary rows selected. If `False`, the count will be the total number of rows returne
(self, distinct: bool = True)
| 775 | return bool(result) |
| 776 | |
| 777 | async def count(self, distinct: bool = True) -> int: |
| 778 | """ |
| 779 | Returns number of rows matching the given criteria |
| 780 | (applied with `filter` and `exclude` if set before). |
| 781 | If `distinct` is `True` (the default), this will return |
| 782 | the number of primary rows selected. If `False`, |
| 783 | the count will be the total number of rows returned |
| 784 | (including extra rows for `one-to-many` or `many-to-many` |
| 785 | left `select_related` table joins). |
| 786 | `False` is the legacy (buggy) behavior for workflows that depend on it. |
| 787 | |
| 788 | :param distinct: flag if the primary table rows should be distinct or not |
| 789 | |
| 790 | :return: number of rows |
| 791 | :rtype: int |
| 792 | """ |
| 793 | expr = self.build_select_expression().alias("subquery_for_count") |
| 794 | expr = sqlalchemy.func.count().select().select_from(expr) # type: ignore |
| 795 | if distinct: |
| 796 | pk_column_name = self.model.get_column_alias(self.model_config.pkname) |
| 797 | expr_distinct = expr.group_by(pk_column_name).alias("subquery_for_group") # type: ignore |
| 798 | expr = sqlalchemy.func.count().select().select_from(expr_distinct) # type: ignore |
| 799 | async with self.model_config.database.get_query_executor() as executor: |
| 800 | result = await executor.fetch_val(expr) # type: ignore |
| 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) |