Skip to content

QuerySet

Chainable query builder for repository data access. QuerySets support filtering, excluding, ordering, pagination, and lookup operations.

See Retrieve Aggregates guide for practical usage.

A chainable, lazy query over one aggregate's or entity's data store.

filter(), exclude(), order_by(), limit(), offset() and only() each return a new QuerySet and fetch nothing. The query runs when you call all(), which returns a ResultSet, or when you call len(), bool() or list() on the QuerySet, iterate over it, or slice it.

The QuerySet keeps a non-empty result of its last run, and iterating or slicing again reuses it. An empty result is not kept, so the query runs again. When the Unit of Work transaction has changed since that run, the query runs again. all() always runs the query again, so call it to see changes made since the last run.

Initialize either with empty preferences (when invoked on an Entity) or carry forward filters and preferences when chained

Source code in src/protean/core/queryset.py
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
def __init__(
    self,
    owner_dao: "DAO",
    domain: "Domain",
    entity_cls: type["BaseEntity"],
    criteria: Q | None = None,
    offset: int = 0,
    limit: int | None = None,  # No limit by default
    order_by: list[str] | str | None = None,
    only_fields: list[str] | None = None,
) -> None:
    """Initialize either with empty preferences (when invoked on an Entity)
    or carry forward filters and preferences when chained
    """
    self._owner_dao = owner_dao
    self._domain = domain
    self._entity_cls = entity_cls
    self._criteria = criteria or Q()
    self._result_cache: ResultSet | None = None
    # The transaction the cache was filled in, and how to fill it again.
    self._result_cache_transaction: object | None = None
    self._refill_cache: Callable[[], ResultSet] | None = None
    self._offset = offset or 0

    # Field selection set via ``only()``. ``None`` means "fetch full
    # rows and materialize entities"; a list means "fetch only these
    # attributes and return read-only ``Record`` objects". Stored as
    # attribute (column) names so adapters can consume it directly.
    self._only_fields: list[str] | None = only_fields

    # If an explicit limit is not provided, use the limit from the entity class
    self._limit = limit or entity_cls.meta_.limit

    # `order_by` could be empty, or a string or a list.
    #   Initialize empty list if `order_by` is None
    #   Convert string to list if `order_by` is a String
    #   Safe-cast list to a list if `order_by` is already a list
    self._order_by: list[str]
    if order_by:
        self._order_by = [order_by] if isinstance(order_by, str) else order_by
    else:
        self._order_by = []

total property

total: int

Return the total number of records

items property

items: list[Any]

Return result values

first property

first: Any | None

Return the first result

last property

last: Any | None

Return the last result

has_next property

has_next: bool

Return True if more pages exist beyond the current one.

has_prev property

has_prev: bool

Return True if this page has items and starts after the first item (offset > 0).

page property

page: int

Return the current page number

page_size property

page_size: int | None

Return the page size

total_pages property

total_pages: int

Return the total number of pages

filter

filter(*args: Any, **kwargs: Any) -> Self

Return a new QuerySet instance with the args ANDed to the existing set.

Source code in src/protean/core/queryset.py
108
109
110
111
112
113
def filter(self, *args: Any, **kwargs: Any) -> Self:
    """
    Return a new QuerySet instance with the args ANDed to the existing
    set.
    """
    return self._filter_or_exclude(False, *args, **kwargs)

exclude

exclude(*args: Any, **kwargs: Any) -> Self

Return a new QuerySet instance that drops every record matching any of the given conditions.

Each keyword and each positional Q is negated on its own and the results are ANDed to the existing set, so exclude(a=1, b=2) keeps NOT a=1 AND NOT b=2. A positional Q with several conditions is negated as a whole: exclude(Q(a=1, b=2)) drops only the records that match both. An empty Q drops nothing.

Source code in src/protean/core/queryset.py
115
116
117
118
119
120
121
122
123
124
125
126
def exclude(self, *args: Any, **kwargs: Any) -> Self:
    """
    Return a new QuerySet instance that drops every record matching any
    of the given conditions.

    Each keyword and each positional ``Q`` is negated on its own and the
    results are ANDed to the existing set, so ``exclude(a=1, b=2)`` keeps
    ``NOT a=1 AND NOT b=2``. A positional ``Q`` with several conditions is
    negated as a whole: ``exclude(Q(a=1, b=2))`` drops only the records
    that match both. An empty ``Q`` drops nothing.
    """
    return self._filter_or_exclude(True, *args, **kwargs)

limit

limit(limit: int | None) -> Self

Limit number of records

Source code in src/protean/core/queryset.py
170
171
172
173
174
175
176
177
178
def limit(self, limit: int | None) -> Self:
    """Limit number of records"""
    clone = self._clone()

    # Assign limit if it is an integer or None
    if isinstance(limit, int) or limit is None:
        clone._limit = limit

    return clone

offset

offset(offset: int) -> Self

Fetch results after offset value

Source code in src/protean/core/queryset.py
180
181
182
183
184
185
186
187
def offset(self, offset: int) -> Self:
    """Fetch results after `offset` value"""
    clone = self._clone()

    if isinstance(offset, int):
        clone._offset = offset

    return clone

order_by

order_by(order_by: list[str] | str) -> Self

Update order_by setting for filter set

Source code in src/protean/core/queryset.py
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
def order_by(self, order_by: list[str] | str) -> Self:
    """Update order_by setting for filter set"""
    clone = self._clone()

    if isinstance(order_by, str):
        order_by = [order_by]

    # Get the attribute name of the field
    # We want to support both field name and attribute name in the query,
    #   so we look for the key name in both fields and attributes.
    #
    # If we don't find it in either, we raise an error.
    new_order_by = []

    for key in order_by:
        # If the key starts with a minus sign, it is a descending order
        reverse = False
        if key.startswith("-"):
            reverse = True
            cleaned_key = key[1:]
        else:
            cleaned_key = key

        attr_name = self._resolve_attribute_name(cleaned_key)

        if reverse:
            new_order_by.append(f"-{attr_name}")
        else:
            new_order_by.append(attr_name)

    clone._order_by.extend(
        item for item in new_order_by if item not in clone._order_by
    )

    return clone

only

only(*field_names: str) -> Self

Return a QuerySet that fetches only the named fields.

The new QuerySet fetches only these columns, plus the identifier, which is always included. It yields read-only Record objects instead of domain entities. A Record has no behavior, runs no invariants and cannot be persisted, so update() and delete() raise NotSupportedError on a QuerySet with a selection.

Calling only() again replaces the selection. Calling it with no arguments clears the selection and restores full entities.

PARAMETER DESCRIPTION
*field_names

Names of the persisted fields to fetch. Field names and attribute names both work.

TYPE: str DEFAULT: ()

RAISES DESCRIPTION
KeyError

A name is not a field or attribute of the entity.

NotSupportedError

A name is not a persisted field, such as an association.

Source code in src/protean/core/queryset.py
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
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
def only(self, *field_names: str) -> Self:
    """Return a QuerySet that fetches only the named fields.

    The new QuerySet fetches only these columns, plus the identifier, which
    is always included. It yields read-only
    [`Record`][protean.core.queryset.Record] objects instead of domain
    entities. A ``Record`` has no behavior, runs no invariants and cannot be
    persisted, so ``update()`` and ``delete()`` raise ``NotSupportedError``
    on a QuerySet with a selection.

    Calling ``only()`` again replaces the selection. Calling it with no
    arguments clears the selection and restores full entities.

    Args:
        *field_names: Names of the persisted fields to fetch. Field names
            and attribute names both work.

    Raises:
        KeyError: A name is not a field or attribute of the entity.
        NotSupportedError: A name is not a persisted field, such as an
            association.
    """
    clone = self._clone()

    # No arguments clears the selection (last call wins).
    if not field_names:
        clone._only_fields = None
        return clone

    entity_attributes = attributes(self._entity_cls)
    resolved: list[str] = []

    def _add(name: str) -> None:
        attr_name = self._resolve_attribute_name(name)

        # Only persisted attributes (real columns) can be projected.
        # Associations and other non-persisted fields have no column to
        # fetch and would make the selection meaningless.
        if attr_name not in entity_attributes:
            raise NotSupportedError(
                f"`.only()` cannot project '{name}' on "
                f"{self._entity_cls.__name__}: it is not a persisted field."
            )

        if attr_name not in resolved:
            resolved.append(attr_name)

    # The identifier is always included so every Record is addressable.
    id_field_obj = id_field(self._entity_cls)
    if id_field_obj is not None:
        # A registered identity field always has its ``field_name`` populated
        # (set during ``__set_name__``); ``None`` only occurs on an unbound Field.
        assert id_field_obj.field_name is not None
        _add(id_field_obj.field_name)

    for name in field_names:
        _add(name)

    clone._only_fields = resolved
    return clone

all

all(with_total: bool = True) -> ResultSet

Primary method to fetch data based on filters

Also trigged when the QuerySet is evaluated by calling one of the following methods
  • len()
  • bool()
  • list()
  • Iteration
  • Slicing

When with_total is False the adapter may skip any expensive total-count computation (e.g. SQL's separate COUNT query); use this when only ResultSet.items is needed and ResultSet.total can be disregarded.

Source code in src/protean/core/queryset.py
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
def all(self, with_total: bool = True) -> "ResultSet":
    """Primary method to fetch data based on filters

    Also trigged when the QuerySet is evaluated by calling one of the following methods:
        * len()
        * bool()
        * list()
        * Iteration
        * Slicing

    When ``with_total`` is ``False`` the adapter may skip any expensive
    total-count computation (e.g. SQL's separate ``COUNT`` query); use this
    when only ``ResultSet.items`` is needed and ``ResultSet.total`` can be
    disregarded.
    """
    logger.debug(f"Query `{self.__class__.__name__}` objects with filters {self}")

    # Destroy any cached results
    self._result_cache = None

    results = self._owner_dao.fetch(
        self._criteria,
        offset=self._offset,
        limit=self._limit,
        order_by=self._order_by,
        with_total=with_total,
        fields=self._only_fields,
    )
    self._cache(results, lambda: self.all(with_total=with_total))
    return results

count

count() -> int

Return the count of records matching the current criteria.

Issues a single SELECT COUNT(*) (or adapter equivalent) without projecting columns or materializing entities. Ignores offset, limit, and order_by since they do not affect the row count.

Source code in src/protean/core/queryset.py
365
366
367
368
369
370
371
372
def count(self) -> int:
    """Return the count of records matching the current criteria.

    Issues a single ``SELECT COUNT(*)`` (or adapter equivalent) without
    projecting columns or materializing entities. Ignores ``offset``,
    ``limit``, and ``order_by`` since they do not affect the row count.
    """
    return self._owner_dao.count(self._criteria)

update

update(
    *data: Any, apply_hooks: bool = True, **kwargs: Any
) -> int

Update every matching aggregate and return how many matched.

.. deprecated:: 0.18.0 The patch-and-persist path is deprecated and is removed in v0.20.0. Load the matched aggregates, invoke a behaviour method on each, and persist each one with repository.add() instead.

Applies the values to each matched aggregate through DAO.update(), which takes the same *data, apply_hooks and keyword arguments. Each aggregate is saved on its own, with its own version check. Outside a Unit of Work, an error on one aggregate, such as ExpectedVersionError, leaves the aggregates before it saved.

RETURNS DESCRIPTION
int

The number of aggregates matched.

RAISES DESCRIPTION
NotSupportedError

The QuerySet has an only() selection.

Source code in src/protean/core/queryset.py
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
def update(self, *data: Any, apply_hooks: bool = True, **kwargs: Any) -> int:
    """Update every matching aggregate and return how many matched.

    .. deprecated:: 0.18.0
        The patch-and-persist path is deprecated and is removed in v0.20.0.
        Load the matched aggregates, invoke a behaviour method on each, and
        persist each one with ``repository.add()`` instead.

    Applies the values to each matched aggregate through
    ``DAO.update()``, which takes the same ``*data``, ``apply_hooks``
    and keyword arguments. Each aggregate is saved on its own, with its own
    version check. Outside a Unit of Work, an error on one aggregate, such
    as ``ExpectedVersionError``, leaves the aggregates before it saved.

    Returns:
        The number of aggregates matched.

    Raises:
        NotSupportedError: The QuerySet has an ``only()`` selection.
    """
    self._reject_if_projected("update")

    # Warn once for the whole bulk call, then drive the silent internal path
    # (``_apply_update``) per row so a batch does not re-warn once per item.
    warn_from_registry("queryset_update", "QuerySet.update()")

    updated_item_count = 0

    items = self.all()

    for item in items:
        self._owner_dao._apply_update(
            item, *data, apply_hooks=apply_hooks, **kwargs
        )
        updated_item_count += 1

    return updated_item_count

raw

raw(query: Any, data: Any = None) -> ResultSet

Run a raw query on the database and return the matching entities.

The query goes to the database as it is, unchecked. Any error from the adapter or the database is raised unchanged. The bundled adapters ignore data; use the provider's raw() to bind values to placeholders.

order_by, offset, limit and any only() selection do not apply. The result always holds full entities, never Record objects.

RAISES DESCRIPTION
NotSupportedError

The provider does not support raw queries.

Source code in src/protean/core/queryset.py
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
def raw(self, query: Any, data: Any = None) -> "ResultSet":
    """Run a raw query on the database and return the matching entities.

    The query goes to the database as it is, unchecked. Any error from the
    adapter or the database is raised unchanged. The bundled adapters
    ignore ``data``; use the provider's ``raw()`` to bind values to
    placeholders.

    ``order_by``, ``offset``, ``limit`` and any ``only()`` selection do not
    apply. The result always holds full entities, never ``Record``
    objects.

    Raises:
        NotSupportedError: The provider does not support raw queries.
    """
    logger.debug(
        f"Query `{self.__class__.__name__}` objects with raw query {query}"
    )

    results = self._owner_dao.raw(query, data)

    # Reset the cache only once the read succeeds, so a raise leaves it as
    # it was.
    self._result_cache = None
    self._cache(results, lambda: self.raw(query, data))
    return results

delete

delete() -> int

Deletes matching objects from the Repository

Does not throw error if no objects are matched.

Returns the number of objects matched (which may not be equal to the number of objects deleted if objects rows already have the new value).

Source code in src/protean/core/queryset.py
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
def delete(self) -> int:
    """Deletes matching objects from the Repository

    Does not throw error if no objects are matched.

    Returns the number of objects matched (which may not be equal to the number of objects
        deleted if objects rows already have the new value).
    """
    self._reject_if_projected("delete")

    # Fetch Model class and connected repository from Domain
    deleted_item_count = 0

    items = self.all()

    for item in items:
        self._owner_dao.delete(item)
        deleted_item_count += 1

    return deleted_item_count

__iter__

__iter__() -> Any

Return results on iteration

Source code in src/protean/core/queryset.py
503
504
505
def __iter__(self) -> Any:
    """Return results on iteration"""
    return iter(self._data)

__len__

__len__() -> int

Return length of results

Source code in src/protean/core/queryset.py
507
508
509
def __len__(self) -> int:
    """Return length of results"""
    return self._data.total

__bool__

__bool__() -> bool

Return True if query results have items

Source code in src/protean/core/queryset.py
511
512
513
def __bool__(self) -> bool:
    """Return True if query results have items"""
    return bool(self._data)

__repr__

__repr__() -> str

Support friendly print of query criteria

Source code in src/protean/core/queryset.py
515
516
517
def __repr__(self) -> str:
    """Support friendly print of query criteria"""
    return f"<{self.__class__.__name__}: entity: {self._entity_cls}, criteria: {self._criteria.deconstruct()}, offset: {self._offset}, limit: {self._limit}, order_by: {self._order_by}>"

__getitem__

__getitem__(k: Any) -> Any

Support slicing of results

Source code in src/protean/core/queryset.py
519
520
521
def __getitem__(self, k: Any) -> Any:
    """Support slicing of results"""
    return self._data.items[k]

__contains__

__contains__(k: Any) -> bool

Support in operations

Source code in src/protean/core/queryset.py
523
524
525
def __contains__(self, k: Any) -> bool:
    """Support `in` operations"""
    return k.id in [item.id for item in self._data.items]

Record

The read-only value type returned by QuerySet.only(). A Record carries a projected subset of a single result's fields. It is not a domain entity: it has no behavior, runs no invariants, and cannot be persisted.

A read-only selection of fields from a single result.

Returned by QuerySet.only instead of a fully materialized domain entity. A Record is intentionally inert: it is not a domain entity, it carries no behavior, runs no invariants, and cannot be persisted. It exists purely to carry a subset of column values on read-optimized paths (counts, cleanups, statistics) without the cost, or the validity guarantees, of a full entity. This keeps the domain model airtight: field selection never produces a partially-valid aggregate.

Access selected values by attribute (record.status) or item (record["status"]). Reading a field that was not selected raises AttributeError / KeyError rather than returning a silent None, so an unselected field is never mistaken for a null value.

Source code in src/protean/core/queryset.py
735
736
737
def __init__(self, entity_name: str, data: dict[str, Any]) -> None:
    object.__setattr__(self, "_entity_name", entity_name)
    object.__setattr__(self, "_data", dict(data))

keys

keys() -> KeysView[str]

Return the projected field names.

Source code in src/protean/core/queryset.py
760
761
762
def keys(self) -> KeysView[str]:
    """Return the projected field names."""
    return self._data.keys()

to_dict

to_dict() -> dict[str, Any]

Return the projected values as a plain dict.

Source code in src/protean/core/queryset.py
764
765
766
def to_dict(self) -> dict[str, Any]:
    """Return the projected values as a plain dict."""
    return dict(self._data)

F

A reference to another column of the same row, for use as the right-hand side of a lookup inside filter()/Q (e.g. filter(retry_count__lt=F("max_retries"))). The in-memory and SQLAlchemy adapters resolve F natively, but the Elasticsearch adapter raises NotImplementedError for F-bearing predicates. See the Retrieve Aggregates guide for usage.

Reference to another column of the same row, for use inside Q lookups.

F lets a filter compare two columns of the same row instead of comparing a column against a literal value::

# column against a literal
query.filter(retry_count__lt=3)

# column against another column
query.filter(retry_count__lt=F("max_retries"))

Only a bare column reference is supported. Arithmetic (F("a") + 1), function calls (Lower(F("email"))), and aggregations are not supported.

The in-memory and SQLAlchemy adapters support F. The Elasticsearch adapter raises NotImplementedError for any predicate that uses F.

Source code in src/protean/utils/query.py
156
157
def __init__(self, name: str) -> None:
    self.name = name

Q

The query-criteria primitive. A Q object wraps one or more field lookups so they can be combined into boolean expressions and passed to filter() and exclude(). Combine Q objects with & (AND), | (OR), and ~ (NOT) to express conditions that keyword arguments alone cannot, for example filter(Q(status="active") | Q(status="pending")). Q is a top-level export: from protean import Q.

Bases: Node

Encapsulate filters as objects that can then be combined logically (using & and |).

Source code in src/protean/utils/query.py
313
314
315
316
317
318
319
320
321
322
323
324
def __init__(
    self,
    *args: Any,
    _connector: str | None = None,
    _negated: bool = False,
    **kwargs: Any,
) -> None:
    super().__init__(
        children=[*args, *sorted(kwargs.items())],
        connector=_connector,
        negated=_negated,
    )

deconstruct

deconstruct() -> tuple[
    str, tuple[Any, ...], dict[str, Any]
]

Deconstruct a Q Object

Source code in src/protean/utils/query.py
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
def deconstruct(self) -> tuple[str, tuple[Any, ...], dict[str, Any]]:
    """Deconstruct a Q Object"""
    path = f"{self.__class__.__module__}.{self.__class__.__name__}"
    args: tuple[Any, ...] = ()
    kwargs: dict[str, Any] = {}

    if len(self.children) == 1 and not isinstance(self.children[0], Q):
        child = self.children[0]
        kwargs = {child[0]: child[1]}
    else:
        args = tuple(self.children)
        if self.connector != self.default:
            kwargs = {"_connector": self.connector}
    if self.negated:
        kwargs["_negated"] = True
    return path, args, kwargs

Cross-adapter conformance

The conformance test suite holds every built-in adapter to the same behaviour for these query-API primitives. Each primitive is gated by a capability tier: an adapter that declares a capability must pass every conformance test tagged with it. See ADR-0023 for the rationale.

Primitive Capability tier Adapters that must pass
count() basic_storage all (including Elasticsearch)
only() projection basic_storage all
isnull lookup basic_storage all
lt / lte lookups basic_storage all
delete_top bounded delete basic_storage all
F() column comparison transactional in-memory + SQL
claim correctness transactional in-memory + SQL
claim no-double-claim (concurrent) atomic_transactions SQL only

F() and claim are gated above basic_storage because Elasticsearch does not support them: it raises NotImplementedError for F-bearing predicates, and its document-versioning makes it unsuitable as a concurrent claim store.