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 class to gather a bunch of criteria and preferences (resultset size, order etc.) before execution.
Internally, a QuerySet can be constructed, filtered, sliced, and generally passed around without actually fetching data. No data fetch actually occurs until you do something to evaluate the queryset.
Once evaluated, a QuerySet typically caches its results. If the data in the database
might have changed, you can get updated results for the same query by calling all() on a
previously evaluated QuerySet.
| ATTRIBUTE | DESCRIPTION |
|---|---|
offset |
Number of records after which Results are fetched
TYPE:
|
limit |
The size the recordset to be pulled from database
TYPE:
|
order_by |
The list of parameters to be used for ordering the results.
Use a
TYPE:
|
excludes_ |
Objects with these properties will be excluded from the results
TYPE:
|
filters |
Filter criteria
TYPE:
|
:return Returns a ResultSet object that holds the query results
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
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 | |
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 there are more values present
has_prev
property
has_prev: bool
Return True if there are previous values present
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) -> QuerySet
Return a new QuerySet instance with the args ANDed to the existing set.
Source code in src/protean/core/queryset.py
109 110 111 112 113 114 | |
exclude
exclude(*args: Any, **kwargs: Any) -> QuerySet
Return a new QuerySet instance with NOT (args) ANDed to the existing set.
Source code in src/protean/core/queryset.py
116 117 118 119 120 121 | |
limit
limit(limit: int | None) -> QuerySet
Limit number of records
Source code in src/protean/core/queryset.py
152 153 154 155 156 157 158 159 160 | |
offset
offset(offset: int) -> QuerySet
Fetch results after offset value
Source code in src/protean/core/queryset.py
162 163 164 165 166 167 168 169 | |
order_by
order_by(order_by: Union[list[str], str]) -> QuerySet
Update order_by setting for filter set
Source code in src/protean/core/queryset.py
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 | |
only
only(*field_names: str) -> QuerySet
Restrict the query to a subset of persisted fields.
Returns a new QuerySet that, when evaluated, fetches only the
requested columns (plus the identifier, which is always included) and
yields read-only :class:Record objects instead of fully materialized
domain entities. This avoids the I/O of loading large columns (e.g.
JSON blobs) on read-optimized paths — counts, cleanups, statistics —
that never need the whole record.
A Record is not a domain entity: it has no behavior, runs no
invariants, and cannot be persisted. It is purely a read-side carrier
of column values. Domain operations must continue to go through full
entities; only() is for field-selection reads.
Calling only() again replaces the selection (selections do not
compose). Calling only() with no arguments clears any selection and
restores full-entity materialization.
:param field_names: Names of persisted fields to project. The identifier is always included automatically. :raises KeyError: if a name is not a field or attribute of the entity. :raises NotSupportedError: if a name resolves to a non-persisted field (e.g. an association), which cannot be projected.
Source code in src/protean/core/queryset.py
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 262 263 264 265 266 267 268 269 | |
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
312 313 314 315 316 317 318 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 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 | |
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
371 372 373 374 375 376 377 378 | |
update
update(*data: Any, **kwargs: Any) -> int
Updates all objects with details given if they match a set of conditions supplied.
This method updates each object individually, to fire callback methods and ensure validations are run.
Returns the number of objects matched (which may not be equal to the number of objects updated if objects rows already have the new value).
Source code in src/protean/core/queryset.py
380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 | |
raw
raw(query: Any, data: Any = None) -> ResultSet
Runs raw query directly on the database and returns Entity objects
Note that this method will raise an exception if the returned objects are not of the Entity type.
query is not checked for correctness or validity, and any errors thrown by the plugin or
database are passed as-is. Data passed will be transferred as-is to the plugin.
All other query options like order_by, offset, limit, and any
only() field selection are ignored for this action; raw() always
returns full Entity objects, never Record objects.
Raises NotSupportedError if the provider does not support raw queries.
Source code in src/protean/core/queryset.py
404 405 406 407 408 409 410 411 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 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 | |
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
457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 | |
__iter__
__iter__() -> Any
Return results on iteration
Source code in src/protean/core/queryset.py
492 493 494 | |
__len__
__len__() -> int
Return length of results
Source code in src/protean/core/queryset.py
496 497 498 | |
__bool__
__bool__() -> bool
Return True if query results have items
Source code in src/protean/core/queryset.py
500 501 502 | |
__repr__
__repr__() -> str
Support friendly print of query criteria
Source code in src/protean/core/queryset.py
504 505 506 507 508 509 510 511 512 513 | |
__getitem__
__getitem__(k: Any) -> Any
Support slicing of results
Source code in src/protean/core/queryset.py
515 516 517 | |
__contains__
__contains__(k: Any) -> bool
Support in operations
Source code in src/protean/core/queryset.py
519 520 521 | |
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 :meth: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
:class:AttributeError / :class: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
731 732 733 | |
keys
keys() -> KeysView[str]
Return the projected field names.
Source code in src/protean/core/queryset.py
756 757 758 | |
to_dict
to_dict() -> dict[str, Any]
Return the projected values as a plain dict.
Source code in src/protean/core/queryset.py
760 761 762 | |
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"))).
Resolved natively by the in-memory and SQLAlchemy adapters; 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 intentionally
out of scope.
Adapter support: the in-memory and SQLAlchemy adapters resolve F to the
referenced column natively. The Elasticsearch adapter raises
NotImplementedError for F-bearing predicates (column-to-column
comparison there needs a Painless script query, which is not implemented);
use the in-memory or SQLAlchemy backend for such filters.
Source code in src/protean/utils/query.py
131 132 | |