Skip to content

order_action

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()"

RandomOrderAction

Bases: OrderAction

Orders the rows of the queried model randomly, created for order_by("?"). It reads no field, so it has no relation path, and like an order on the model's own field it replaces the default primary key order.

Source code in ormar/queryset/actions/order_action.py
Python
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
class RandomOrderAction(OrderAction):
    """
    Orders the rows of the queried model randomly, created for
    ``order_by("?")``. It reads no field, so it has no relation path, and like
    an order on the model's own field it replaces the default primary key
    order.
    """

    def __init__(self, model_cls: type["Model"]) -> None:
        super().__init__(order_str=RANDOM_ORDER, model_cls=model_cls)

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

    def _random_order(self) -> str:
        return self.source_model.ormar_config.database.rules.random_order

    def get_field_name_text(self) -> str:
        """
        :return: the random function, which keys the ordering of the limited
            sub query of the main model
        :rtype: str
        """
        return self._random_order()

    def get_min_or_max(self) -> sqlalchemy.sql.expression.TextClause:
        """
        :return: the random function, it needs no aggregate in the grouped
            limit sub query
        :rtype: sqlalchemy.sql.elements.TextClause
        """
        return self.get_text_clause()

    def get_text_clause(self) -> sqlalchemy.sql.expression.TextClause:
        """
        :return: the random function of the database dialect
        :rtype: sqlalchemy.sql.elements.TextClause
        """
        return order_text_clause(self._random_order())

get_field_name_text()

Returns:

Type Description
str

the random function, which keys the ordering of the limited sub query of the main model

Source code in ormar/queryset/actions/order_action.py
Python
224
225
226
227
228
229
230
def get_field_name_text(self) -> str:
    """
    :return: the random function, which keys the ordering of the limited
        sub query of the main model
    :rtype: str
    """
    return self._random_order()

get_min_or_max()

Returns:

Type Description
sqlalchemy.sql.elements.TextClause

the random function, it needs no aggregate in the grouped limit sub query

Source code in ormar/queryset/actions/order_action.py
Python
232
233
234
235
236
237
238
def get_min_or_max(self) -> sqlalchemy.sql.expression.TextClause:
    """
    :return: the random function, it needs no aggregate in the grouped
        limit sub query
    :rtype: sqlalchemy.sql.elements.TextClause
    """
    return self.get_text_clause()

get_text_clause()

Returns:

Type Description
sqlalchemy.sql.elements.TextClause

the random function of the database dialect

Source code in ormar/queryset/actions/order_action.py
Python
240
241
242
243
244
245
def get_text_clause(self) -> sqlalchemy.sql.expression.TextClause:
    """
    :return: the random function of the database dialect
    :rtype: sqlalchemy.sql.elements.TextClause
    """
    return order_text_clause(self._random_order())

expand_pk_orders(model_cls, columns)

Turn an order_by list into order actions, expanding pk orders (also after relations and from Model.pk.asc() / Model.rel.pk.desc()) into the primary key fields with :func:order_actions_for.

Parameters:

Name Type Description Default
model_cls type[Model]

ordered model

required
columns list[Any]

order strings, OrderAction, RandomOrder or Random instances

required

Returns:

Type Description
list[OrderAction]

order actions with pk expanded

Source code in ormar/queryset/actions/order_action.py
Python
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
def expand_pk_orders(model_cls: type["Model"], columns: list[Any]) -> list[OrderAction]:
    """
    Turn an ``order_by`` list into order actions, expanding ``pk`` orders (also
    after relations and from ``Model.pk.asc()`` / ``Model.rel.pk.desc()``) into
    the primary key fields with :func:`order_actions_for`.

    :param model_cls: ordered model
    :type model_cls: type[Model]
    :param columns: order strings, ``OrderAction``, ``RandomOrder`` or
        ``Random`` instances
    :type columns: list[Any]
    :return: order actions with ``pk`` expanded
    :rtype: list[OrderAction]
    """
    expanded: list[OrderAction] = []
    for column in columns:
        if isinstance(column, (RandomOrder, Random)):
            expanded.append(RandomOrderAction(model_cls=model_cls))
        elif isinstance(column, str):
            expanded.extend(order_actions_for(order_str=column, model_cls=model_cls))
        elif column.field_name == "pk":
            expanded.extend(
                order_actions_for(
                    order_str=column.query_str,
                    model_cls=model_cls,
                    nulls_ordering=column.nulls_ordering,
                )
            )
        else:
            expanded.append(column)
    return expanded

order_actions_for(order_str, model_cls, alias=None, nulls_ordering=None)

Build the order actions for one order string, expanding pk (also after relations) into the primary key fields of the model it points at, in key order, and ? into a random order::

Text Only
1
2
3
4
"-pk"         -> ["-tenant_id", "-number"]
"-stock__pk"  -> ["-stock__code", "-stock__sku"]
"shop__pk"    -> ["shop__id"]
"?"           -> [RandomOrderAction]

Parameters:

Name Type Description Default
order_str str

order string, - prefixed for descending order

required
model_cls type[Model]

model the order string starts from

required
alias Optional[str]

table alias of the ordered model, if already known

None
nulls_ordering Optional[str]

optional nulls placement, "first" or "last"

None

Returns:

Type Description
list[OrderAction]

order actions, one per key field for a pk order

Source code in ormar/queryset/actions/order_action.py
Python
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
def order_actions_for(
    order_str: str,
    model_cls: type["Model"],
    alias: Optional[str] = None,
    nulls_ordering: Optional[str] = None,
) -> list[OrderAction]:
    """
    Build the order actions for one order string, expanding ``pk`` (also after
    relations) into the primary key fields of the model it points at, in key
    order, and ``?`` into a random order::

        "-pk"         -> ["-tenant_id", "-number"]
        "-stock__pk"  -> ["-stock__code", "-stock__sku"]
        "shop__pk"    -> ["shop__id"]
        "?"           -> [RandomOrderAction]

    :param order_str: order string, ``-`` prefixed for descending order
    :type order_str: str
    :param model_cls: model the order string starts from
    :type model_cls: type[Model]
    :param alias: table alias of the ordered model, if already known
    :type alias: Optional[str]
    :param nulls_ordering: optional nulls placement, ``"first"`` or ``"last"``
    :type nulls_ordering: Optional[str]
    :return: order actions, one per key field for a ``pk`` order
    :rtype: list[OrderAction]
    """
    if order_str.lstrip("-") == RANDOM_ORDER:
        return [RandomOrderAction(model_cls=model_cls)]
    action = OrderAction(
        order_str=order_str,
        model_cls=model_cls,
        alias=alias,
        nulls_ordering=nulls_ordering,
    )
    if action.field_name != "pk":
        return [action]
    prefix = order_str[: -len("pk")]
    return [
        OrderAction(
            order_str=f"{prefix}{field}",
            model_cls=model_cls,
            alias=alias,
            nulls_ordering=nulls_ordering,
        )
        for field in action.target_model.ormar_config.pk.fields
    ]

order_text_clause(expression) cached

Builds a text clause for an ORDER BY expression, cached as text clauses are immutable and the same orderings (e.g. default pk sort) repeat on every query.

Parameters:

Name Type Description Default
expression str

raw ORDER BY expression

required

Returns:

Type Description
sqlalchemy.sql.expression.TextClause

text clause for the expression

Source code in ormar/queryset/actions/order_action.py
Python
19
20
21
22
23
24
25
26
27
28
29
30
@lru_cache(maxsize=2048)
def order_text_clause(expression: str) -> sqlalchemy.sql.expression.TextClause:
    """
    Builds a text clause for an ORDER BY expression, cached as text clauses are
    immutable and the same orderings (e.g. default pk sort) repeat on every query.

    :param expression: raw ORDER BY expression
    :type expression: str
    :return: text clause for the expression
    :rtype: sqlalchemy.sql.expression.TextClause
    """
    return text(expression)

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()