Skip to content

actions

FilterAction

Bases: QueryAction

Represents a single WHERE predicate on a queryset.

Created for each key=value (or key__op=value) passed to filter(...) / exclude(...) and to filtering shortcuts like get(...) / first(...).

Source code in ormar/queryset/actions/filter_action.py
Python
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
class FilterAction(QueryAction):
    """
    Represents a single WHERE predicate on a queryset.

    Created for each ``key=value`` (or ``key__op=value``) passed to
    ``filter(...)`` / ``exclude(...)`` and to filtering shortcuts like
    ``get(...)`` / ``first(...)``.
    """

    def __init__(self, filter_str: str, value: Any, model_cls: type["Model"]) -> None:
        super().__init__(query_str=filter_str, model_cls=model_cls)
        self.expression_columns: dict[str, SelectAction] = {}
        if isinstance(value, Expression):
            value = value._node()
            if self.operator not in ("exact", "ne", "gt", "gte", "lt", "lte"):
                raise QueryDefinitionError(
                    f"Expressions only take exact, ne, gt, gte, lt and lte filters, "
                    f"not '{self.operator}'"
                )
            self.expression_columns = expression_columns(node=value, model=model_cls)
        self.filter_value = value
        self._escape_characters_in_clause()

    def path_actions(self) -> list[QueryAction]:
        """
        :return: the action and the fields its expression reads, each resolving
            one relation path to a joined table
        :rtype: list[QueryAction]
        """
        return [self, *self.expression_columns.values()]

    def update_select_related(self, select_related: list[str]) -> list[str]:
        """
        Add the joins of the filtered field and of the fields its expression
        reads (see ``QueryAction.update_select_related``).

        :param select_related: list of relation join strings
        :type select_related: list[str]
        :return: list of relation joins with implied joins from filter added
        :rtype: list[str]
        """
        select_related = super().update_select_related(select_related=select_related)
        for column in self.expression_columns.values():
            select_related = column.update_select_related(select_related=select_related)
        return select_related

    def has_escaped_characters(self) -> bool:
        """Check if value is a string that contains characters to escape"""
        return isinstance(self.filter_value, str) and any(
            c for c in ESCAPE_CHARACTERS if c in self.filter_value
        )

    def _split_value_into_parts(self, query_str: str) -> None:
        self.operator, path = split_filter_key(key=query_str)
        self.field_name = path[-1]
        self.related_parts = path[:-1]

    def _escape_characters_in_clause(self) -> None:
        """
        Escapes the special characters ["%", "_"] if needed.
        Adds `%` for `like` queries.

        :raises QueryDefinitionError: if contains or icontains is used with
        ormar model instance
        :return: escaped value and flag if escaping is needed
        :rtype: tuple[Any, bool]
        """
        self.has_escaped_character = False
        if self.operator in [
            "contains",
            "icontains",
            "startswith",
            "istartswith",
            "endswith",
            "iendswith",
        ]:
            if isinstance(self.filter_value, ormar.Model):
                raise QueryDefinitionError(
                    "You cannot use contains and icontains with instance of the Model"
                )
            self.has_escaped_character = self.has_escaped_characters()
            if self.has_escaped_character:
                self._escape_chars()
            self._prefix_suffix_quote()

    def _escape_chars(self) -> None:
        """Actually replaces chars to escape in value"""
        for char in ESCAPE_CHARACTERS:
            self.filter_value = self.filter_value.replace(char, f"\\{char}")

    def _prefix_suffix_quote(self) -> None:
        """
        Adds % to the beginning of the value if operator checks for containment and not
        starts with.

        Adds % to the end of the value if operator checks for containment and not
        end with.
        :return:
        :rtype:
        """
        prefix = "%" if "start" not in self.operator else ""
        sufix = "%" if "end" not in self.operator else ""
        self.filter_value = f"{prefix}{self.filter_value}{sufix}"

    def bound_value(self) -> Any:
        """
        Return the value bound to the query: an ormar Model is replaced by its
        value it is referenced by (its primary key or the foreign key's
        ``to_field``), so ``filter(author=author)`` binds ``author.pk``.

        ``filter_value`` itself is left untouched, so the action can be read
        again on every call to collect the value for a cached template.

        :return: value to bind
        :rtype: Any
        """
        if isinstance(self.filter_value, ormar.Model):
            field = self.target_model.ormar_config.model_fields.get(self.field_name)
            if (
                field is not None
                and field.is_relation
                and not field.virtual
                and not field.is_multi
            ):
                relation_field = cast("ForeignKeyField", field)
                return relation_field.target_value_of(related=self.filter_value)
            return self.filter_value.pk
        return self.filter_value

    def binds_slot(self) -> bool:
        """
        Return whether the value is bound as a parameter: SQLAlchemy renders
        ``None`` (``IS NULL``), booleans and ``isnull`` checks into the SQL text.

        Only values that are bound can get a named slot in a statement
        template. The others stay in the SQL text and become part of the
        template's cache key instead (see ``templates.value_cache_key``)::

            filter(name="a")  # True  -> name = :ormar_p0
            filter(name=None)  # False -> name IS NULL

        :return: True when the value is sent as a bound parameter
        :rtype: bool
        """
        value = self.bound_value()
        return (
            self.operator != "isnull"
            and value is not None
            and not isinstance(value, bool)
        )

    def get_text_clause(self, binder: Optional["SlotBinder"] = None) -> TextClause:
        """
        Escapes characters if it's required.
        Substitutes values of the models if value is a ormar Model with its pk value.
        Compiles the clause.

        :param binder: names the bound value for statement templates
            (``= :ormar_p0`` instead of an anonymous parameter), if given
        :type binder: Optional[SlotBinder]
        :return: complied and escaped clause
        :rtype: sqlalchemy.sql.elements.TextClause
        """
        value = self.bound_value()
        op_attr = FILTER_OPERATORS[self.operator]
        if self.operator == "isnull":
            op_attr = "is_" if value else "isnot"
            filter_value = None
        elif isinstance(value, Expression):
            filter_value = expression_clause(
                node=value,
                columns=self.expression_columns,
                slot=binder.slots[id(self)] if binder is not None else None,
            )
        else:
            filter_value = value
            if binder is not None and self.binds_slot():
                filter_value = binder.bind(action=self, value=value)
        clause = getattr(self.aliased_column, op_attr)(filter_value)
        if self.has_escaped_character:
            clause.modifiers["escape"] = "\\"
        return clause

binds_slot()

Return whether the value is bound as a parameter: SQLAlchemy renders None (IS NULL), booleans and isnull checks into the SQL text.

Only values that are bound can get a named slot in a statement template. The others stay in the SQL text and become part of the template's cache key instead (see templates.value_cache_key)::

Text Only
1
2
filter(name="a")  # True  -> name = :ormar_p0
filter(name=None)  # False -> name IS NULL

Returns:

Type Description
bool

True when the value is sent as a bound parameter

Source code in ormar/queryset/actions/filter_action.py
Python
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
def binds_slot(self) -> bool:
    """
    Return whether the value is bound as a parameter: SQLAlchemy renders
    ``None`` (``IS NULL``), booleans and ``isnull`` checks into the SQL text.

    Only values that are bound can get a named slot in a statement
    template. The others stay in the SQL text and become part of the
    template's cache key instead (see ``templates.value_cache_key``)::

        filter(name="a")  # True  -> name = :ormar_p0
        filter(name=None)  # False -> name IS NULL

    :return: True when the value is sent as a bound parameter
    :rtype: bool
    """
    value = self.bound_value()
    return (
        self.operator != "isnull"
        and value is not None
        and not isinstance(value, bool)
    )

bound_value()

Return the value bound to the query: an ormar Model is replaced by its value it is referenced by (its primary key or the foreign key's to_field), so filter(author=author) binds author.pk.

filter_value itself is left untouched, so the action can be read again on every call to collect the value for a cached template.

Returns:

Type Description
Any

value to bind

Source code in ormar/queryset/actions/filter_action.py
Python
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
def bound_value(self) -> Any:
    """
    Return the value bound to the query: an ormar Model is replaced by its
    value it is referenced by (its primary key or the foreign key's
    ``to_field``), so ``filter(author=author)`` binds ``author.pk``.

    ``filter_value`` itself is left untouched, so the action can be read
    again on every call to collect the value for a cached template.

    :return: value to bind
    :rtype: Any
    """
    if isinstance(self.filter_value, ormar.Model):
        field = self.target_model.ormar_config.model_fields.get(self.field_name)
        if (
            field is not None
            and field.is_relation
            and not field.virtual
            and not field.is_multi
        ):
            relation_field = cast("ForeignKeyField", field)
            return relation_field.target_value_of(related=self.filter_value)
        return self.filter_value.pk
    return self.filter_value

get_text_clause(binder=None)

Escapes characters if it's required. Substitutes values of the models if value is a ormar Model with its pk value. Compiles the clause.

Parameters:

Name Type Description Default
binder Optional[SlotBinder]

names the bound value for statement templates (= :ormar_p0 instead of an anonymous parameter), if given

None

Returns:

Type Description
sqlalchemy.sql.elements.TextClause

complied and escaped clause

Source code in ormar/queryset/actions/filter_action.py
Python
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
def get_text_clause(self, binder: Optional["SlotBinder"] = None) -> TextClause:
    """
    Escapes characters if it's required.
    Substitutes values of the models if value is a ormar Model with its pk value.
    Compiles the clause.

    :param binder: names the bound value for statement templates
        (``= :ormar_p0`` instead of an anonymous parameter), if given
    :type binder: Optional[SlotBinder]
    :return: complied and escaped clause
    :rtype: sqlalchemy.sql.elements.TextClause
    """
    value = self.bound_value()
    op_attr = FILTER_OPERATORS[self.operator]
    if self.operator == "isnull":
        op_attr = "is_" if value else "isnot"
        filter_value = None
    elif isinstance(value, Expression):
        filter_value = expression_clause(
            node=value,
            columns=self.expression_columns,
            slot=binder.slots[id(self)] if binder is not None else None,
        )
    else:
        filter_value = value
        if binder is not None and self.binds_slot():
            filter_value = binder.bind(action=self, value=value)
    clause = getattr(self.aliased_column, op_attr)(filter_value)
    if self.has_escaped_character:
        clause.modifiers["escape"] = "\\"
    return clause

has_escaped_characters()

Check if value is a string that contains characters to escape

Source code in ormar/queryset/actions/filter_action.py
Python
126
127
128
129
130
def has_escaped_characters(self) -> bool:
    """Check if value is a string that contains characters to escape"""
    return isinstance(self.filter_value, str) and any(
        c for c in ESCAPE_CHARACTERS if c in self.filter_value
    )

path_actions()

Returns:

Type Description
list[QueryAction]

the action and the fields its expression reads, each resolving one relation path to a joined table

Source code in ormar/queryset/actions/filter_action.py
Python
103
104
105
106
107
108
109
def path_actions(self) -> list[QueryAction]:
    """
    :return: the action and the fields its expression reads, each resolving
        one relation path to a joined table
    :rtype: list[QueryAction]
    """
    return [self, *self.expression_columns.values()]

Add the joins of the filtered field and of the fields its expression reads (see QueryAction.update_select_related).

Parameters:

Name Type Description Default
select_related list[str]

list of relation join strings

required

Returns:

Type Description
list[str]

list of relation joins with implied joins from filter added

Source code in ormar/queryset/actions/filter_action.py
Python
111
112
113
114
115
116
117
118
119
120
121
122
123
124
def update_select_related(self, select_related: list[str]) -> list[str]:
    """
    Add the joins of the filtered field and of the fields its expression
    reads (see ``QueryAction.update_select_related``).

    :param select_related: list of relation join strings
    :type select_related: list[str]
    :return: list of relation joins with implied joins from filter added
    :rtype: list[str]
    """
    select_related = super().update_select_related(select_related=select_related)
    for column in self.expression_columns.values():
        select_related = column.update_select_related(select_related=select_related)
    return select_related

OrderAction

Bases: QueryAction

Represents a single ORDER BY directive on a queryset.

Created when order_by(...) or Field.asc() / Field.desc() is used, and internally to apply the default primary-key ordering.

Source code in ormar/queryset/actions/order_action.py
Python
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
class OrderAction(QueryAction):
    """
    Represents a single ORDER BY directive on a queryset.

    Created when ``order_by(...)`` or ``Field.asc()`` / ``Field.desc()`` is
    used, and internally to apply the default primary-key ordering.
    """

    def __init__(
        self,
        order_str: str,
        model_cls: type["Model"],
        alias: Optional[str] = None,
        nulls_ordering: Optional[str] = None,
    ) -> None:
        self.direction: str = ""
        super().__init__(query_str=order_str, model_cls=model_cls)
        self.is_source_model_order = False
        if alias:
            self.table_prefix = alias
        if self.source_model == self.target_model and "__" not in self.related_str:
            self.is_source_model_order = True
        self.nulls_ordering = nulls_ordering

    @property
    def field_alias(self) -> str:
        return self.target_model.get_column_alias(self.field_name)

    @property
    def field_aliases(self) -> tuple[str, ...]:
        """
        :return: columns the field is ordered by: its column, or every column
            of a foreign key stored in several columns
        :rtype: tuple[str, ...]
        """
        return self.target_model.get_column_aliases(field_name=self.field_name)

    def get_field_name_text(self) -> str:
        """
        Escapes characters if it's required.
        Substitutes values of the models if value is a ormar Model with its pk value.
        Compiles the clause.

        :return: complied and escaped clause
        :rtype: sqlalchemy.sql.elements.TextClause
        """
        prefix = f"{self.table_prefix}_" if self.table_prefix else ""
        return f"{prefix}{self.table.name}.{self.field_alias}"

    def get_min_or_max(self) -> sqlalchemy.sql.expression.TextClause:
        """
        Used in limit sub queries where you need to use aggregated functions
        in order to order by columns not included in group by. For postgres bool
        field it's using bool_or function as aggregates does not work with this type
        of columns.

        :return: min or max function to order
        :rtype: sqlalchemy.sql.elements.TextClause
        """
        prefix = f"{self.table_prefix}_" if self.table_prefix else ""
        config = self.target_model.ormar_config
        function = config.database.rules.ordering_aggregate(
            field_type=config.model_fields[self.field_name].__type__,
            descending=bool(self.direction),
        )
        suffix = " desc" if self.direction else ""
        return text(
            ", ".join(
                f"{function}({prefix}{self.table.name}.{alias}){suffix}"
                for alias in self.field_aliases
            )
        )

    def get_text_clause(self) -> sqlalchemy.sql.expression.TextClause:
        """
        Escapes characters if it's required.
        Substitutes values of the models if value is a ormar Model with its pk value.
        Compiles the clause.

        :return: complied and escaped clause
        :rtype: sqlalchemy.sql.elements.TextClause
        """
        dialect = self.target_model.ormar_config.database.dialect
        quoter = dialect.identifier_preparer.quote
        prefix = f"{self.table_prefix}_" if self.table_prefix else ""
        table_name = quoter(f"{prefix}{self.table.name}")
        return order_text_clause(
            ", ".join(
                self._build_order_expression(f"{table_name}.{quoter(alias)}")
                for alias in self.field_aliases
            )
        )

    def _build_order_expression(self, full_column: str) -> str:
        """
        Builds the final ORDER BY expression for a fully-qualified column,
        optionally including a `NULLS FIRST`/`NULLS LAST` annotation (emulated
        by the dialect rules where the syntax is missing).

        :param full_column: fully-qualified, quoted column reference
        :type full_column: str
        :return: ORDER BY expression as raw SQL text
        :rtype: str
        """
        direction = f" {self.direction}" if self.direction else ""
        base = f"{full_column}{direction}"
        if self.nulls_ordering is None:
            return base
        return self.target_model.ormar_config.database.rules.nulls_order(
            full_column=full_column, ordered=base, nulls_ordering=self.nulls_ordering
        )

    def _split_value_into_parts(self, order_str: str) -> None:
        if order_str.startswith("-"):
            self.direction = "desc"
            order_str = order_str[1:]
        parts = order_str.split("__")
        self.field_name = parts[-1]
        self.related_parts = parts[:-1]

    @classmethod
    def from_model_defaults(cls, model_cls: type["Model"]) -> list["OrderAction"]:
        """
        Builds the default list of ``OrderAction`` instances from a model's
        ``OrmarConfig.orders_by`` (which always contains at least the primary
        key, populated by the metaclass).

        :param model_cls: model class whose defaults should be used
        :type model_cls: type["Model"]
        :return: list of default OrderAction instances for the model
        :rtype: list[OrderAction]
        """
        return [
            action
            for name in model_cls.ormar_config.orders_by
            for action in order_actions_for(order_str=str(name), model_cls=model_cls)
        ]

    def flipped(self) -> "OrderAction":
        """
        Returns a shallow copy of this order action with the sort direction
        and any `NULLS FIRST`/`NULLS LAST` annotation inverted.

        Used by reverse slicing to turn an ASC/DESC ordering into its mirror
        image so that ``LIMIT N`` fetches rows from the tail of the original
        ordering. Callers are responsible for reversing the result list in
        memory afterwards so the caller-visible ordering is preserved.

        :return: new OrderAction with flipped direction and nulls ordering
        :rtype: OrderAction
        """
        flipped = copy.copy(self)
        flipped.direction = "" if self.direction == "desc" else "desc"
        if self.nulls_ordering == "first":
            flipped.nulls_ordering = "last"
        elif self.nulls_ordering == "last":
            flipped.nulls_ordering = "first"
        return flipped

    def check_if_filter_apply(self, target_model: type["Model"], alias: str) -> bool:
        """
        Checks filter conditions to find if they apply to current join.

        :param target_model: model which is now processed
        :type target_model: type["Model"]
        :param alias: prefix of the relation
        :type alias: str
        :return: result of the check
        :rtype: bool
        """
        return target_model == self.target_model and alias == self.table_prefix

field_aliases property

Returns:

Type Description
tuple[str, ...]

columns the field is ordered by: its column, or every column of a foreign key stored in several columns

check_if_filter_apply(target_model, alias)

Checks filter conditions to find if they apply to current join.

Parameters:

Name Type Description Default
target_model type[Model]

model which is now processed

required
alias str

prefix of the relation

required

Returns:

Type Description
bool

result of the check

Source code in ormar/queryset/actions/order_action.py
Python
192
193
194
195
196
197
198
199
200
201
202
203
def check_if_filter_apply(self, target_model: type["Model"], alias: str) -> bool:
    """
    Checks filter conditions to find if they apply to current join.

    :param target_model: model which is now processed
    :type target_model: type["Model"]
    :param alias: prefix of the relation
    :type alias: str
    :return: result of the check
    :rtype: bool
    """
    return target_model == self.target_model and alias == self.table_prefix

flipped()

Returns a shallow copy of this order action with the sort direction and any NULLS FIRST/NULLS LAST annotation inverted.

Used by reverse slicing to turn an ASC/DESC ordering into its mirror image so that LIMIT N fetches rows from the tail of the original ordering. Callers are responsible for reversing the result list in memory afterwards so the caller-visible ordering is preserved.

Returns:

Type Description
OrderAction

new OrderAction with flipped direction and nulls ordering

Source code in ormar/queryset/actions/order_action.py
Python
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
def flipped(self) -> "OrderAction":
    """
    Returns a shallow copy of this order action with the sort direction
    and any `NULLS FIRST`/`NULLS LAST` annotation inverted.

    Used by reverse slicing to turn an ASC/DESC ordering into its mirror
    image so that ``LIMIT N`` fetches rows from the tail of the original
    ordering. Callers are responsible for reversing the result list in
    memory afterwards so the caller-visible ordering is preserved.

    :return: new OrderAction with flipped direction and nulls ordering
    :rtype: OrderAction
    """
    flipped = copy.copy(self)
    flipped.direction = "" if self.direction == "desc" else "desc"
    if self.nulls_ordering == "first":
        flipped.nulls_ordering = "last"
    elif self.nulls_ordering == "last":
        flipped.nulls_ordering = "first"
    return flipped

from_model_defaults(model_cls) classmethod

Builds the default list of OrderAction instances from a model's OrmarConfig.orders_by (which always contains at least the primary key, populated by the metaclass).

Parameters:

Name Type Description Default
model_cls type[Model]

model class whose defaults should be used

required

Returns:

Type Description
list[OrderAction]

list of default OrderAction instances for the model

Source code in ormar/queryset/actions/order_action.py
Python
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
@classmethod
def from_model_defaults(cls, model_cls: type["Model"]) -> list["OrderAction"]:
    """
    Builds the default list of ``OrderAction`` instances from a model's
    ``OrmarConfig.orders_by`` (which always contains at least the primary
    key, populated by the metaclass).

    :param model_cls: model class whose defaults should be used
    :type model_cls: type["Model"]
    :return: list of default OrderAction instances for the model
    :rtype: list[OrderAction]
    """
    return [
        action
        for name in model_cls.ormar_config.orders_by
        for action in order_actions_for(order_str=str(name), model_cls=model_cls)
    ]

get_field_name_text()

Escapes characters if it's required. Substitutes values of the models if value is a ormar Model with its pk value. Compiles the clause.

Returns:

Type Description
sqlalchemy.sql.elements.TextClause

complied and escaped clause

Source code in ormar/queryset/actions/order_action.py
Python
70
71
72
73
74
75
76
77
78
79
80
def get_field_name_text(self) -> str:
    """
    Escapes characters if it's required.
    Substitutes values of the models if value is a ormar Model with its pk value.
    Compiles the clause.

    :return: complied and escaped clause
    :rtype: sqlalchemy.sql.elements.TextClause
    """
    prefix = f"{self.table_prefix}_" if self.table_prefix else ""
    return f"{prefix}{self.table.name}.{self.field_alias}"

get_min_or_max()

Used in limit sub queries where you need to use aggregated functions in order to order by columns not included in group by. For postgres bool field it's using bool_or function as aggregates does not work with this type of columns.

Returns:

Type Description
sqlalchemy.sql.elements.TextClause

min or max function to order

Source code in ormar/queryset/actions/order_action.py
Python
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
def get_min_or_max(self) -> sqlalchemy.sql.expression.TextClause:
    """
    Used in limit sub queries where you need to use aggregated functions
    in order to order by columns not included in group by. For postgres bool
    field it's using bool_or function as aggregates does not work with this type
    of columns.

    :return: min or max function to order
    :rtype: sqlalchemy.sql.elements.TextClause
    """
    prefix = f"{self.table_prefix}_" if self.table_prefix else ""
    config = self.target_model.ormar_config
    function = config.database.rules.ordering_aggregate(
        field_type=config.model_fields[self.field_name].__type__,
        descending=bool(self.direction),
    )
    suffix = " desc" if self.direction else ""
    return text(
        ", ".join(
            f"{function}({prefix}{self.table.name}.{alias}){suffix}"
            for alias in self.field_aliases
        )
    )

get_text_clause()

Escapes characters if it's required. Substitutes values of the models if value is a ormar Model with its pk value. Compiles the clause.

Returns:

Type Description
sqlalchemy.sql.elements.TextClause

complied and escaped clause

Source code in ormar/queryset/actions/order_action.py
Python
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
def get_text_clause(self) -> sqlalchemy.sql.expression.TextClause:
    """
    Escapes characters if it's required.
    Substitutes values of the models if value is a ormar Model with its pk value.
    Compiles the clause.

    :return: complied and escaped clause
    :rtype: sqlalchemy.sql.elements.TextClause
    """
    dialect = self.target_model.ormar_config.database.dialect
    quoter = dialect.identifier_preparer.quote
    prefix = f"{self.table_prefix}_" if self.table_prefix else ""
    table_name = quoter(f"{prefix}{self.table.name}")
    return order_text_clause(
        ", ".join(
            self._build_order_expression(f"{table_name}.{quoter(alias)}")
            for alias in self.field_aliases
        )
    )

RandomOrder

Random order of the queried model, the ormar.random() form of order_by("?").

Source code in ormar/queryset/actions/order_action.py
Python
248
249
250
251
252
253
254
255
class RandomOrder:
    """
    Random order of the queried model, the ``ormar.random()`` form of
    ``order_by("?")``.
    """

    def __repr__(self) -> str:
        return "ormar.random()"

SelectAction

Bases: QueryAction

Represents a single column target for an aggregate function on a queryset.

Created when .min() / .max() / .sum() / .avg() is called, optionally traversing relations via __. Also resolves the fields read by column expressions (see expression_columns).

Source code in ormar/queryset/actions/select_action.py
Python
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
class SelectAction(QueryAction):
    """
    Represents a single column target for an aggregate function on a queryset.

    Created when ``.min()`` / ``.max()`` / ``.sum()`` / ``.avg()`` is called,
    optionally traversing relations via ``__``. Also resolves the fields read
    by column expressions (see ``expression_columns``).
    """

    def __init__(self, select_str: str, model_cls: type["Model"]) -> None:
        super().__init__(query_str=select_str, model_cls=model_cls)

    def _split_value_into_parts(self, order_str: str) -> None:
        parts = order_str.split("__")
        self.field_name = parts[-1]
        self.related_parts = parts[:-1]

    @property
    def is_numeric(self) -> bool:
        return self.get_target_field_type() in [int, float, decimal.Decimal]

    def get_target_field_type(self) -> Any:
        return self.target_model.ormar_config.model_fields[self.field_name].__type__

    def get_text_clause(self) -> sqlalchemy.sql.expression.ColumnClause:
        alias = f"{self.table_prefix}_" if self.table_prefix else ""
        return sqlalchemy.column(f"{alias}{self.field_name}")

    def apply_func(
        self, func: Callable, use_label: bool = True
    ) -> sqlalchemy.sql.expression.ColumnElement:
        result = func(self.get_text_clause())
        if use_label:
            rel_prefix = f"{self.related_str}__" if self.related_str else ""
            result = result.label(f"{rel_prefix}{self.field_name}")
        return result

random()

Order the rows randomly, same as "?"::

Text Only
1
await User.objects.order_by(ormar.random()).limit(3).all()

Returns:

Type Description
RandomOrder

random order to pass to order_by()

Source code in ormar/queryset/actions/order_action.py
Python
258
259
260
261
262
263
264
265
266
267
def random() -> RandomOrder:
    """
    Order the rows randomly, same as ``"?"``::

        await User.objects.order_by(ormar.random()).limit(3).all()

    :return: random order to pass to ``order_by()``
    :rtype: RandomOrder
    """
    return RandomOrder()