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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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:
|
| 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 | |
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 | |
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 | |
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 |
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 | |
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 | |
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 | |
__iter__
__iter__() -> Any
Return results on iteration
Source code in src/protean/core/queryset.py
503 504 505 | |
__len__
__len__() -> int
Return length of results
Source code in src/protean/core/queryset.py
507 508 509 | |
__bool__
__bool__() -> bool
Return True if query results have items
Source code in src/protean/core/queryset.py
511 512 513 | |
__repr__
__repr__() -> str
Support friendly print of query criteria
Source code in src/protean/core/queryset.py
515 516 517 | |
__getitem__
__getitem__(k: Any) -> Any
Support slicing of results
Source code in src/protean/core/queryset.py
519 520 521 | |
__contains__
__contains__(k: Any) -> bool
Support in operations
Source code in src/protean/core/queryset.py
523 524 525 | |
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 | |
keys
keys() -> KeysView[str]
Return the projected field names.
Source code in src/protean/core/queryset.py
760 761 762 | |
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 | |
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 | |
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 | |
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 | |
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.