Skip to content

clause

FilterGroup

Filter groups are used in complex queries condition to group and and or clauses in where condition

Source code in ormar/queryset/clause.py
Python
 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
class FilterGroup:
    """
    Filter groups are used in complex queries condition to group and and or
    clauses in where condition
    """

    def __init__(
        self,
        *args: Any,
        _filter_type: FilterType = FilterType.AND,
        _exclude: bool = False,
        **kwargs: Any,
    ) -> None:
        self.filter_type = _filter_type
        self.exclude = _exclude
        self._nested_groups: list["FilterGroup"] = list(args)
        self._resolved = False
        self.is_source_model_filter = False
        self._kwargs_dict = kwargs
        self.actions: list[FilterAction] = []

    def __and__(self, other: "FilterGroup") -> "FilterGroup":
        return FilterGroup(self, other)

    def __or__(self, other: "FilterGroup") -> "FilterGroup":
        return FilterGroup(self, other, _filter_type=FilterType.OR)

    def __invert__(self) -> "FilterGroup":
        self.exclude = not self.exclude
        return self

    def resolve(
        self,
        model_cls: type["Model"],
        select_related: Optional[list] = None,
        filter_clauses: Optional[list] = None,
    ) -> tuple[list[FilterAction], list[str]]:
        """
        Resolves the FilterGroups actions to use proper target model, replace
        complex relation prefixes if needed and nested groups also resolved.

        :param model_cls: model from which the query is run
        :type model_cls: type["Model"]
        :param select_related: list of models to join
        :type select_related: list[str]
        :param filter_clauses: list of filter conditions
        :type filter_clauses: list[FilterAction]
        :return: list of filter conditions and select_related list
        :rtype: tuple[list[FilterAction], list[str]]
        """
        select_related = select_related if select_related is not None else []
        filter_clauses = filter_clauses if filter_clauses is not None else []
        qryclause = QueryClause(
            model_cls=model_cls,
            select_related=select_related,
            filter_clauses=filter_clauses,
        )
        own_filter_clauses, select_related = qryclause.prepare_filter(
            _own_only=True, **self._kwargs_dict
        )
        self.actions = own_filter_clauses
        filter_clauses = filter_clauses + own_filter_clauses
        self._resolved = True
        if self._nested_groups:
            for group in self._nested_groups:
                filter_clauses, select_related = group.resolve(
                    model_cls=model_cls,
                    select_related=select_related,
                    filter_clauses=filter_clauses,
                )
        return filter_clauses, select_related

    def _iter(self) -> Generator:
        """
        Iterates all actions in a tree
        :return: generator yielding from own actions and nested groups
        :rtype: Generator
        """
        for group in self._nested_groups:
            yield from group._iter()
        yield from self.actions

    def _get_text_clauses(
        self, binder: Optional["SlotBinder"] = None
    ) -> list[Union[sqlalchemy.sql.expression.TextClause, ColumnElement[Any]]]:
        """
        Helper to return list of text queries from actions and nested groups

        :param binder: names bound values for statement templates, if given
        :type binder: Optional[SlotBinder]
        :return: list of text queries from actions and nested groups
        :rtype: list[sqlalchemy.sql.elements.TextClause]
        """
        return [x.get_text_clause(binder=binder) for x in self._nested_groups] + [
            x.get_text_clause(binder=binder) for x in self.actions
        ]

    def get_text_clause(
        self, binder: Optional["SlotBinder"] = None
    ) -> ColumnElement[bool]:
        """
        Returns all own actions and nested groups conditions compiled and joined
        inside parentheses.
        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 bound values for statement templates, if given
        :type binder: Optional[SlotBinder]
        :return: complied and escaped clause
        :rtype: sqlalchemy.sql.elements.TextClause
        """
        clauses = self._get_text_clauses(binder=binder)
        if self.filter_type == FilterType.AND:
            clause = sqlalchemy.sql.and_(*clauses).self_group()
        else:
            clause = sqlalchemy.sql.or_(*clauses).self_group()
        if self.exclude:
            clause = sqlalchemy.sql.not_(clause)
        return clause

get_text_clause(binder=None)

Returns all own actions and nested groups conditions compiled and joined inside parentheses. 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 bound values for statement templates, if given

None

Returns:

Type Description
sqlalchemy.sql.elements.TextClause

complied and escaped clause

Source code in ormar/queryset/clause.py
Python
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
def get_text_clause(
    self, binder: Optional["SlotBinder"] = None
) -> ColumnElement[bool]:
    """
    Returns all own actions and nested groups conditions compiled and joined
    inside parentheses.
    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 bound values for statement templates, if given
    :type binder: Optional[SlotBinder]
    :return: complied and escaped clause
    :rtype: sqlalchemy.sql.elements.TextClause
    """
    clauses = self._get_text_clauses(binder=binder)
    if self.filter_type == FilterType.AND:
        clause = sqlalchemy.sql.and_(*clauses).self_group()
    else:
        clause = sqlalchemy.sql.or_(*clauses).self_group()
    if self.exclude:
        clause = sqlalchemy.sql.not_(clause)
    return clause

resolve(model_cls, select_related=None, filter_clauses=None)

Resolves the FilterGroups actions to use proper target model, replace complex relation prefixes if needed and nested groups also resolved.

Parameters:

Name Type Description Default
model_cls type[Model]

model from which the query is run

required
select_related Optional[list]

list of models to join

None
filter_clauses Optional[list]

list of filter conditions

None

Returns:

Type Description
tuple[list[FilterAction], list[str]]

list of filter conditions and select_related list

Source code in ormar/queryset/clause.py
Python
 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
def resolve(
    self,
    model_cls: type["Model"],
    select_related: Optional[list] = None,
    filter_clauses: Optional[list] = None,
) -> tuple[list[FilterAction], list[str]]:
    """
    Resolves the FilterGroups actions to use proper target model, replace
    complex relation prefixes if needed and nested groups also resolved.

    :param model_cls: model from which the query is run
    :type model_cls: type["Model"]
    :param select_related: list of models to join
    :type select_related: list[str]
    :param filter_clauses: list of filter conditions
    :type filter_clauses: list[FilterAction]
    :return: list of filter conditions and select_related list
    :rtype: tuple[list[FilterAction], list[str]]
    """
    select_related = select_related if select_related is not None else []
    filter_clauses = filter_clauses if filter_clauses is not None else []
    qryclause = QueryClause(
        model_cls=model_cls,
        select_related=select_related,
        filter_clauses=filter_clauses,
    )
    own_filter_clauses, select_related = qryclause.prepare_filter(
        _own_only=True, **self._kwargs_dict
    )
    self.actions = own_filter_clauses
    filter_clauses = filter_clauses + own_filter_clauses
    self._resolved = True
    if self._nested_groups:
        for group in self._nested_groups:
            filter_clauses, select_related = group.resolve(
                model_cls=model_cls,
                select_related=select_related,
                filter_clauses=filter_clauses,
            )
    return filter_clauses, select_related

NullsOrdering

Bases: str, Enum

Nulls placement options for the .order_by() queries.

Source code in ormar/queryset/clause.py
Python
27
28
29
30
31
class NullsOrdering(str, Enum):
    """Nulls placement options for the `.order_by()` queries."""

    FIRST = "first"
    LAST = "last"

QueryClause

Constructs FilterActions from strings passed as arguments

Source code in ormar/queryset/clause.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
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
class QueryClause:
    """
    Constructs FilterActions from strings passed as arguments
    """

    def __init__(
        self, model_cls: type["Model"], filter_clauses: list, select_related: list
    ) -> None:
        self._select_related = select_related[:]
        self.filter_clauses = filter_clauses[:]

        self.model_cls = model_cls
        self.table = self.model_cls.ormar_config.table

    def prepare_filter(  # noqa: A003
        self, _own_only: bool = False, **kwargs: Any
    ) -> tuple[list[FilterAction], list[str]]:
        """
        Main external access point that processes the clauses into sqlalchemy text
        clauses and updates select_related list with implicit related tables
        mentioned in select_related strings but not included in select_related.

        :param _own_only:
        :type _own_only:
        :param kwargs: key, value pair with column names and values
        :type kwargs: Any
        :return: tuple with list of where clauses and updated select_related list
        :rtype: tuple[list[sqlalchemy.sql.elements.TextClause], list[str]]
        """
        filter_clauses, select_related = self._populate_filter_clauses(
            _own_only=_own_only, **kwargs
        )

        return filter_clauses, select_related

    def _populate_filter_clauses(
        self, _own_only: bool, **kwargs: Any
    ) -> tuple[list[FilterAction], list[str]]:
        """
        Iterates all clauses and extracts used operator and field from related
        models if needed. Based on the chain of related names the target table
        is determined and the final clause is escaped if needed and compiled.

        :param kwargs: key, value pair with column names and values
        :type kwargs: Any
        :return: tuple with list of where clauses and updated select_related list
        :rtype: tuple[list[sqlalchemy.sql.elements.TextClause], list[str]]
        """
        filter_clauses = self.filter_clauses
        own_filter_clauses = []
        select_related = list(self._select_related)

        for key, value in kwargs.items():
            actions = (
                pk_filter_actions(model_cls=self.model_cls, name=key, value=value)
                or multi_column_filter_actions(
                    model_cls=self.model_cls, name=key, value=value
                )
                or [FilterAction(filter_str=key, value=value, model_cls=self.model_cls)]
            )
            for filter_action in actions:
                select_related = filter_action.update_select_related(
                    select_related=select_related
                )
                own_filter_clauses.append(filter_action)

        if _own_only:
            return own_filter_clauses, select_related
        return filter_clauses + own_filter_clauses, select_related

prepare_filter(_own_only=False, **kwargs)

Main external access point that processes the clauses into sqlalchemy text clauses and updates select_related list with implicit related tables mentioned in select_related strings but not included in select_related.

Parameters:

Name Type Description Default
_own_only bool
False
kwargs Any

key, value pair with column names and values

{}

Returns:

Type Description
tuple[list[sqlalchemy.sql.elements.TextClause], list[str]]

tuple with list of where clauses and updated select_related list

Source code in ormar/queryset/clause.py
Python
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
def prepare_filter(  # noqa: A003
    self, _own_only: bool = False, **kwargs: Any
) -> tuple[list[FilterAction], list[str]]:
    """
    Main external access point that processes the clauses into sqlalchemy text
    clauses and updates select_related list with implicit related tables
    mentioned in select_related strings but not included in select_related.

    :param _own_only:
    :type _own_only:
    :param kwargs: key, value pair with column names and values
    :type kwargs: Any
    :return: tuple with list of where clauses and updated select_related list
    :rtype: tuple[list[sqlalchemy.sql.elements.TextClause], list[str]]
    """
    filter_clauses, select_related = self._populate_filter_clauses(
        _own_only=_own_only, **kwargs
    )

    return filter_clauses, select_related

and_(*args, **kwargs)

Construct and filter from nested groups and keyword arguments

Parameters:

Name Type Description Default
args FilterGroup

nested filter groups

()
kwargs Any

fields names and proper value types

{}

Returns:

Type Description
ormar.queryset.clause.FilterGroup

FilterGroup ready to be resolved

Source code in ormar/queryset/clause.py
Python
170
171
172
173
174
175
176
177
178
179
180
181
def and_(*args: FilterGroup, **kwargs: Any) -> FilterGroup:
    """
    Construct and filter from nested groups and keyword arguments

    :param args: nested filter groups
    :type args: tuple[FilterGroup]
    :param kwargs: fields names and proper value types
    :type kwargs: Any
    :return: FilterGroup ready to be resolved
    :rtype: ormar.queryset.clause.FilterGroup
    """
    return FilterGroup(_filter_type=FilterType.AND, *args, **kwargs)

key_parts_of(key, value)

Split a key value used in a filter into the raw value of each key column (related models in relation parts are replaced by the values they are referenced by), rejecting composite values with a None part (a key with a missing part identifies no row).

Parameters:

Name Type Description Default
key PrimaryKey

primary key filtered on

required
value Any

key value

required

Returns:

Type Description
tuple[Any, ...]

key parts in key column order

Raises:

Type Description
QueryDefinitionError

if the value doesn't match the key

Source code in ormar/queryset/clause.py
Python
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
def key_parts_of(key: "PrimaryKey", value: Any) -> tuple[Any, ...]:
    """
    Split a key value used in a filter into the raw value of each key column
    (related models in relation parts are replaced by the values they are
    referenced by), rejecting composite values with a ``None`` part (a key
    with a missing part identifies no row).

    :raises QueryDefinitionError: if the value doesn't match the key
    :param key: primary key filtered on
    :type key: PrimaryKey
    :param value: key value
    :type value: Any
    :return: key parts in key column order
    :rtype: tuple[Any, ...]
    """
    parts = key.flat_parts(value=value)
    if key.is_composite and None in parts:
        raise QueryDefinitionError(
            f"{key.owner.__name__} composite primary key value cannot contain "
            f"None: {value!r}"
        )
    return parts

multi_column_filter_actions(model_cls, name, value)

Turn a filter on a foreign key stored in several columns (also through relations) into a row-value filter on its columns::

Text Only
1
2
3
order=Order(1, 7)       -> (ord_tenant, ord_no) IN ((1, 7))
order__in=[(1, 7)]      -> (ord_tenant, ord_no) IN ((1, 7))
order__isnull=True      -> ord_tenant IS NULL AND ord_no IS NULL

Parameters:

Name Type Description Default
model_cls type[Model]

model the filter starts from

required
name str

filter key

required
value Any

filter value

required

Returns:

Type Description
Optional[list[FilterAction]]

filter actions, None if the key is not such a filter

Raises:

Type Description
QueryDefinitionError

for other operators

Source code in ormar/queryset/clause.py
Python
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
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
def multi_column_filter_actions(
    model_cls: type["Model"], name: str, value: Any
) -> Optional[list[FilterAction]]:
    """
    Turn a filter on a foreign key stored in several columns (also through
    relations) into a row-value filter on its columns::

        order=Order(1, 7)       -> (ord_tenant, ord_no) IN ((1, 7))
        order__in=[(1, 7)]      -> (ord_tenant, ord_no) IN ((1, 7))
        order__isnull=True      -> ord_tenant IS NULL AND ord_no IS NULL

    :raises QueryDefinitionError: for other operators
    :param model_cls: model the filter starts from
    :type model_cls: type[Model]
    :param name: filter key
    :type name: str
    :param value: filter value
    :type value: Any
    :return: filter actions, ``None`` if the key is not such a filter
    :rtype: Optional[list[FilterAction]]
    """
    operator, path = split_filter_key(key=name)
    target = model_cls
    field = None
    for part in path:
        field = target.ormar_config.model_fields.get(part)
        if field is None or not field.is_relation:
            return None
        target = field.to
    if (
        field is None
        or not field.kind.holds_columns
        or len(cast("ForeignKeyField", field).link.pairs) == 1
    ):
        return None
    relation_field = cast("ForeignKeyField", field)
    prefix = "".join(f"{part}__" for part in path[:-1])
    if operator == "exact" and value is None:
        (operator, value) = ("isnull", True)
    if operator == "isnull":
        return [
            KeyNullFilterAction(
                prefix=prefix,
                values=value,
                model_cls=model_cls,
                anchor=path[-1],
                columns=relation_field.link.source_columns(),
            )
        ]
    if operator not in ("exact", "in"):
        raise QueryDefinitionError(
            f"Only =, __in and __isnull lookups are supported on "
            f"{'__'.join(path)}, a foreign key stored in several columns."
        )
    items = [value] if operator == "exact" else list(value)
    values = [
        tuple(relation_field.link.values_for(related=item).values()) for item in items
    ]
    if any(None in key for key in values):
        raise QueryDefinitionError(
            f"Filter {name} needs a value for each column of the relation, "
            f"got {value!r}."
        )
    return [
        KeyInFilterAction(
            prefix=prefix,
            values=values,
            model_cls=model_cls,
            anchor=path[-1],
            columns=relation_field.link.source_columns(),
        )
    ]

or_(*args, **kwargs)

Construct or filter from nested groups and keyword arguments

Parameters:

Name Type Description Default
args FilterGroup

nested filter groups

()
kwargs Any

fields names and proper value types

{}

Returns:

Type Description
ormar.queryset.clause.FilterGroup

FilterGroup ready to be resolved

Source code in ormar/queryset/clause.py
Python
156
157
158
159
160
161
162
163
164
165
166
167
def or_(*args: FilterGroup, **kwargs: Any) -> FilterGroup:
    """
    Construct or filter from nested groups and keyword arguments

    :param args: nested filter groups
    :type args: tuple[FilterGroup]
    :param kwargs: fields names and proper value types
    :type kwargs: Any
    :return: FilterGroup ready to be resolved
    :rtype: ormar.queryset.clause.FilterGroup
    """
    return FilterGroup(_filter_type=FilterType.OR, *args, **kwargs)

pk_filter_actions(model_cls, name, value)

Turn a filter on pk (also through relations, author__pk=1) into filters on the primary key fields of the model it points at::

Text Only
1
2
3
4
pk=4             -> id=4
pk__gt=4         -> id__gt=4
pk=(1, 7)        -> (tenant_id, number) IN ((1, 7))  (composite key)
pk__in=[(1, 7)]  -> (tenant_id, number) IN ((1, 7))  (composite key)

Parameters:

Name Type Description Default
model_cls type[Model]

queried model

required
name str

filter keyword

required
value Any

filter value

required

Returns:

Type Description
Optional[list[FilterAction]]

filter actions, None if the keyword is not a pk lookup

Raises:

Type Description
QueryDefinitionError

for operators other than in on a composite key, values not matching the key, or pk after a field that is not a relation

Source code in ormar/queryset/clause.py
Python
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
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
317
318
319
320
321
def pk_filter_actions(
    model_cls: type["Model"], name: str, value: Any
) -> Optional[list[FilterAction]]:
    """
    Turn a filter on ``pk`` (also through relations, ``author__pk=1``) into
    filters on the primary key fields of the model it points at::

        pk=4             -> id=4
        pk__gt=4         -> id__gt=4
        pk=(1, 7)        -> (tenant_id, number) IN ((1, 7))  (composite key)
        pk__in=[(1, 7)]  -> (tenant_id, number) IN ((1, 7))  (composite key)

    :raises QueryDefinitionError: for operators other than ``in`` on a
        composite key, values not matching the key, or ``pk`` after a field
        that is not a relation
    :param model_cls: queried model
    :type model_cls: type[Model]
    :param name: filter keyword
    :type name: str
    :param value: filter value
    :type value: Any
    :return: filter actions, ``None`` if the keyword is not a ``pk`` lookup
    :rtype: Optional[list[FilterAction]]
    """
    parts = name.split("__")
    if "pk" not in parts:
        return None
    position = parts.index("pk")
    prefix = "".join(f"{part}__" for part in parts[:position])
    operator = "__".join(parts[position + 1 :])
    target = model_cls
    for part in parts[:position]:
        field = target.ormar_config.model_fields.get(part)
        if field is None or not field.is_relation:
            raise QueryDefinitionError(
                f"pk lookup {name} must follow relations, {part} is not a relation "
                f"of {target.__name__}."
            )
        target = field.to
    key = target.ormar_config.pk
    if key.is_composite and operator in ("", "exact"):
        key_value = key_parts_of(key=key, value=value)
        return [
            KeyInFilterAction(prefix=prefix, values=[key_value], model_cls=model_cls)
        ]
    if operator in ("", "exact"):
        (part,) = key_parts_of(key=key, value=value)
        return [
            FilterAction(
                filter_str=f"{prefix}{key.fields[0]}", value=part, model_cls=model_cls
            )
        ]
    if not key.is_composite:
        return [
            FilterAction(
                filter_str=f"{prefix}{key.fields[0]}__{operator}",
                value=value,
                model_cls=model_cls,
            )
        ]
    if operator != "in":
        raise QueryDefinitionError(
            f"Only pk=... and pk__in=... lookups are supported on the composite "
            f"primary key of {target.__name__}, got {name}."
        )
    values = [key_parts_of(key=key, value=item) for item in value]
    return [KeyInFilterAction(prefix=prefix, values=values, model_cls=model_cls)]