Queries¶
Model.where(...) and Model.select() return a Query — an immutable, chainable builder that executes when awaited via all(), first(), count(), exists(), update(), or delete(). Predicates are lambda-first (User.where(lambda t: t.age >= 18)), col() is the compatibility bridge for operator-shaped predicates, and direct operator style is deprecated for v0.14.0 removal. For migration steps, see Migrating to v0.12.0.
Query
¶
Bases: Generic[T]
Build and execute fluent ORM queries.
Attributes:
| Name | Type | Description |
|---|---|---|
model_cls |
Model class used to hydrate results. |
|
where_clause |
list[QueryNode]
|
Accumulated filter nodes for the query. |
order_by_clause |
list[dict[str, str]]
|
Sort definitions sent to the Rust core. |
Source code in src/ferro/query/builder.py
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 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 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 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 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 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 396 397 398 399 400 401 402 403 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 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 | |
Attributes¶
model_cls = model_cls
instance-attribute
¶
where_clause = []
instance-attribute
¶
order_by_clause = []
instance-attribute
¶
Functions¶
__init__(model_cls, using=None, session=None)
¶
Initialize a query for a model class.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_cls
|
Type[T]
|
Model class that defines the target table. |
required |
Examples:
Source code in src/ferro/query/builder.py
where(node)
¶
Add a filter condition to the query.
The recommended style is a lambda predicate of shape
Callable[[QueryProxy[T]], QueryNode]. The lambda receives a
fresh :class:QueryProxy whose attributes return
:class:FieldProxy instances, so lambda t: t.archived == False
builds a comparison without static-typing friction. A prebuilt
:class:QueryNode is also accepted, built either with
:func:ferro.query.col (the type-safe escape hatch that preserves
operator shape) or with operator syntax on class attributes. The
bare operator form (User.where(User.age >= 18)) is deprecated and
on the v0.14.0 removal track. It does not
type-check statically:
the class attribute types as the field type, so the comparison
resolves to bool, not QueryNode.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
node
|
QueryNode | Predicate[T]
|
A predicate callable or a |
required |
Returns:
| Type | Description |
|---|---|
Query[T]
|
The current Query instance for chaining. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If |
Examples:
>>> q1 = User.where(lambda t: t.archived == False) # noqa: E712
>>> q2 = User.where(lambda t: t.id == 1)
>>> isinstance(q1, Query) and isinstance(q2, Query)
True
Source code in src/ferro/query/builder.py
order_by(field, direction='asc')
¶
Add an ordering clause to the query
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
field
|
Any
|
The field to order by (e.g., User.username). |
required |
direction
|
str
|
The direction of the sort ("asc" or "desc"). |
'asc'
|
Returns:
| Type | Description |
|---|---|
Query[T]
|
The current Query instance for chaining. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If direction is not "asc" or "desc". |
Examples:
>>> query = User.select().order_by(User.username, "desc")
>>> query.order_by_clause[-1]["direction"]
'desc'
Source code in src/ferro/query/builder.py
limit(value)
¶
offset(value)
¶
all()
async
¶
Return all model instances that match the current query
Returns:
| Type | Description |
|---|---|
list[T]
|
A list of model instances. |
Examples:
>>> users = await User.where(lambda t: t.active == True).all() # noqa: E712
>>> isinstance(users, list)
True
Source code in src/ferro/query/builder.py
count()
async
¶
Return the number of records that match the current query
Returns:
| Type | Description |
|---|---|
int
|
The count of matching records. |
Examples:
>>> total = await User.where(lambda t: t.active == True).count() # noqa: E712
>>> isinstance(total, int)
True
Source code in src/ferro/query/builder.py
update(**fields)
async
¶
Update all records matching the current query
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
**fields
|
Field names and values to update. |
{}
|
Returns:
| Type | Description |
|---|---|
int
|
The number of records updated. |
Examples:
>>> updated = await User.where(lambda t: t.id == 1).update(name="Taylor")
>>> isinstance(updated, int)
True
Source code in src/ferro/query/builder.py
first()
async
¶
Return the first matching record, or None
Returns:
| Type | Description |
|---|---|
T | None
|
A model instance or None. |
Examples:
>>> user = await User.select().order_by(User.id).first()
>>> user is None or isinstance(user, User)
True
Source code in src/ferro/query/builder.py
delete()
async
¶
Delete all records matching the current query
Returns:
| Type | Description |
|---|---|
int
|
The number of records deleted. |
Examples:
>>> deleted = await User.where(lambda t: t.disabled == True).delete() # noqa: E712
>>> isinstance(deleted, int)
True
Source code in src/ferro/query/builder.py
exists()
async
¶
Return whether at least one record matches the current query
Returns:
| Type | Description |
|---|---|
bool
|
True if records exist, otherwise False. |
Examples:
>>> found = await User.where(lambda t: t.email == "a@b.com").exists()
>>> isinstance(found, bool)
True
Source code in src/ferro/query/builder.py
add(*instances)
async
¶
Add links to a many-to-many relationship
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*instances
|
Any
|
Target model instances that provide an |
()
|
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If the query is not bound to a many-to-many context. |
Examples:
>>> user = await User.create(email="taylor@example.com")
>>> admin = await Group.create(name="admin")
>>> staff = await Group.create(name="staff")
>>> await user.groups.add(admin, staff)
Source code in src/ferro/query/builder.py
remove(*instances)
async
¶
Remove links from a many-to-many relationship
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*instances
|
Any
|
Target model instances that provide an |
()
|
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If the query is not bound to a many-to-many context. |
Examples:
>>> user = await User.create(email="taylor@example.com")
>>> admin = await Group.create(name="admin")
>>> await user.groups.remove(admin)
Source code in src/ferro/query/builder.py
clear()
async
¶
Clear all links in a many-to-many relationship
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If the query is not bound to a many-to-many context. |
Examples:
Source code in src/ferro/query/builder.py
col(value)
¶
Treat a model class attribute as a typed query column.
At runtime Ferro's metaclass replaces Model.field with a
:class:FieldProxy, so Model.field is already a FieldProxy when
accessed on the class. Static type checkers, however, see the field's
Pydantic-annotated type (bool, int, ...). That makes expressions
like Model.archived == False resolve to bool statically, even
though the runtime value is a QueryNode.
col() is runtime-identity for FieldProxy inputs and statically
narrows the return type to FieldProxy[T], so col(Model.archived) ==
False type-checks as QueryNode. Use it when a single attribute
trips your type checker; for new code, prefer the lambda predicate API
on :meth:Query.where.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
TField
|
A model class attribute (already a |
required |
Returns:
| Type | Description |
|---|---|
FieldProxy[TField]
|
The same object, statically typed as |
Raises:
| Type | Description |
|---|---|
TypeError
|
If |
Examples:
Source code in src/ferro/query/nodes.py
QueryProxy
¶
Bases: Generic[TModel]
Lazy attribute proxy used by lambda predicates passed to Query.where.
A fresh QueryProxy is constructed each time a lambda predicate is
evaluated. Any attribute access returns a :class:FieldProxy for the
accessed name, so lambda t: t.archived == False builds a
:class:QueryNode without ever asking the model class what type
archived is. The TModel type parameter exists so user-supplied
lambdas can narrow t to a specific model in static analysis; the
proxy itself ignores the parameter at runtime.
The proxy attribute return type is intentionally FieldProxy[Any] for
now — wiring per-field types through a lambda parameter requires
@dataclass_transform plumbing on the metaclass, which is outside this
feature's scope.
Examples:
Source code in src/ferro/query/nodes.py
Predicate = Callable[[QueryProxy[TModel]], QueryNode]
module-attribute
¶
Type alias for lambda predicates accepted by :meth:Query.where.