def _get_order_bys(self) -> None: # noqa: CCR001 """ Triggers construction of order bys if they are given. Otherwise by default each table is sorted by a primary key column asc. """ alias = self.next_alias current_table_sorted = False if f"{alias}_{self.next_model.get_name()}" in self.already_sorted: current_table_sorted = True if self.order_columns: for condition in self.order_columns: if condition.check_if_filter_apply( target_model=self.next_model, alias=alias): current_table_sorted = True self.sorted_orders[condition] = condition.get_text_clause() self.already_sorted[ f"{self.next_alias}_{self.next_model.get_name()}"] = condition if self.target_field.orders_by and not current_table_sorted: current_table_sorted = True for order_by in self.target_field.orders_by: alias, model = self._get_alias_and_model(order_by=order_by) clause = ormar.OrderAction(order_str=order_by, model_cls=model, alias=alias) self.sorted_orders[clause] = clause.get_text_clause() self.already_sorted[f"{alias}_{model.get_name()}"] = clause if not current_table_sorted and not self.target_field.is_multi: self._set_default_primary_key_order_by()
def _set_default_primary_key_order_by(self) -> None: clause = ormar.OrderAction( order_str=self.next_model.Meta.pkname, model_cls=self.next_model, alias=self.next_alias, ) self.sorted_orders[clause] = clause.get_text_clause()
def _apply_default_model_sorting(self) -> None: """ Applies orders_by from model Meta class (if provided), if it was not provided it was filled by metaclass so it's always there and falls back to pk column """ for order_by in self.model_cls.Meta.orders_by: clause = ormar.OrderAction(order_str=order_by, model_cls=self.model_cls) self.sorted_orders[clause] = clause.get_text_clause()
def apply_order_bys_for_primary_model(self) -> None: # noqa: CCR001 """ Applies order_by queries on main model when it's used as a subquery. That way the subquery with limit and offset only on main model has proper sorting applied and correct models are fetched. """ if self.order_columns: for clause in self.order_columns: if clause.is_source_model_order: self.sorted_orders[clause] = clause.get_text_clause() else: clause = ormar.OrderAction( order_str=self.model_cls.Meta.pkname, model_cls=self.model_cls ) self.sorted_orders[clause] = clause.get_text_clause()