query
Fluent query builder for model reference records.
Provides a read-only, lazy-evaluated query API over cached model records. All filtering, ordering, and pagination happens in-memory on the already-loaded Pydantic models - no new storage or network calls are introduced.
Usage::
from horde_model_reference import ModelReferenceManager
manager = ModelReferenceManager()
results = (
manager.query("image_generation")
.where(nsfw=False, baseline="stable_diffusion_xl")
.tags_any(["realistic", "generalist"])
.order_by("size_on_disk_bytes")
.limit(10)
.to_list()
)
_COMPARISON_OPS
module-attribute
_COMPARISON_OPS: dict[str, Callable[[Any, Any], bool]] = {
"lt": lt,
"lte": le,
"gt": gt,
"gte": ge,
"ne": ne,
"in": lambda val, choices: val in choices,
"contains": lambda val, item: item in val,
}
__all__
module-attribute
__all__ = [
"ControlNetFieldName",
"ControlNetQuery",
"GenericFieldName",
"ImageGenFieldName",
"ImageGenerationQuery",
"ModelQuery",
"TextGenFieldName",
"TextModelQuery",
"build_controlnet_query",
"build_cross_category_query",
"build_image_query",
"build_query",
"build_text_query",
]
GenericFieldName
GenericFieldName = Literal[
"record_type",
"name",
"description",
"version",
"finetune_series",
"metadata",
"config",
"model_classification",
]
ImageGenFieldName
ImageGenFieldName = Literal[
"record_type",
"name",
"description",
"version",
"finetune_series",
"metadata",
"config",
"model_classification",
"inpainting",
"baseline",
"optimization",
"tags",
"showcases",
"min_bridge_version",
"trigger",
"homepage",
"nsfw",
"style",
"requirements",
"size_on_disk_bytes",
]
TextGenFieldName
TextGenFieldName = Literal[
"record_type",
"name",
"description",
"version",
"finetune_series",
"metadata",
"config",
"model_classification",
"baseline",
"parameters_count",
"nsfw",
"style",
"display_name",
"url",
"tags",
"instruct_format",
"settings",
"text_model_group",
]
ControlNetFieldName
ControlNetFieldName = Literal[
"record_type",
"name",
"description",
"version",
"finetune_series",
"metadata",
"config",
"model_classification",
"controlnet_style",
]
HasTags
Bases: Protocol
Protocol for record types that have a tags field.
Satisfied by ImageGenerationModelRecord, TextGenerationModelRecord,
VideoGenerationModelRecord, and AudioGenerationModelRecord.
Source code in src/horde_model_reference/query.py
HasBaseline
Bases: Protocol
Protocol for record types that have a baseline field.
Satisfied by ImageGenerationModelRecord, TextGenerationModelRecord,
VideoGenerationModelRecord, and AudioGenerationModelRecord.
Source code in src/horde_model_reference/query.py
ModelQuery
Lazy, immutable query builder over a sequence of model records.
Every fluent method returns a new instance (via Self) so that
partially-built queries can be safely reused. Subclasses automatically
preserve their concrete type through the chain thanks to type(self)
dispatch in _clone.
Provenance ("sources"): each record may carry a source id describing where it
came from. When sources is None (the common, canonical-only case) every
record is treated as originating from :data:~horde_model_reference.source_consts.HORDE_SOURCE_ID
and there is zero overhead. When records are merged from multiple sources the
manager supplies an aligned sources sequence (canonical-first); results are
de-duplicated by name keeping the first (highest-priority) occurrence, so the
canonical source wins collisions by default. Use :meth:duplicate_names /
:meth:has_duplicate_names to detect when a collision occurred.
Source code in src/horde_model_reference/query.py
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 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 | |
_predicates
instance-attribute
_sources
instance-attribute
_source_predicates
instance-attribute
_source_predicates: Sequence[Callable[[str], bool]] = (
list(source_predicates) if source_predicates else []
)
_source_status
instance-attribute
_source_status: dict[str, SourceOutcome] | None = (
dict(source_status)
if source_status is not None
else None
)
__init__
__init__(
records: Sequence[T],
record_type: type[GenericModelRecord],
*,
predicates: Sequence[Callable[..., bool]] | None = None,
sort_key: str | None = None,
sort_descending: bool = False,
offset_value: int = 0,
limit_value: int | None = None,
sources: Sequence[str] | None = None,
source_predicates: Sequence[Callable[[str], bool]]
| None = None,
source_status: Mapping[str, SourceOutcome]
| None = None,
) -> None
Source code in src/horde_model_reference/query.py
_clone
_clone(
records: Sequence[T] | None = None,
record_type: type[GenericModelRecord] | None = None,
predicates: Sequence[Callable[..., bool]] | None = None,
sort_key: str | None = None,
sort_descending: bool | None = None,
offset_value: int | None = None,
limit_value: int | None = None,
source_predicates: Sequence[Callable[[str], bool]]
| None = None,
) -> Self
Create a shallow copy with optional overrides.
Uses type(self) so that subclasses (TextModelQuery,
ImageGenerationQuery, etc.) automatically get back their own
concrete type without needing to override this method.
_records, _sources and _source_status are passed through unchanged
(fluent methods only ever adjust predicates/sort/pagination), so the records
stay aligned with their provenance and the per-source outcome map is preserved.
Source code in src/horde_model_reference/query.py
where
Filter records by field equality, comparison operators, or Predicate objects.
Supports three styles that can be freely mixed in one call:
- Keyword equality/comparison (Django-style suffixes):
where(nsfw=False, size_on_disk_bytes__gt=1_000_000_000) - Field-ref predicates (typed DSL):
where(ImageFields.nsfw == false, ImageFields.size_on_disk_bytes > 1_000_000_000) - Composed predicates (boolean algebra):
where((ImageFields.nsfw == false) & (ImageFields.baseline == "stable_diffusion_xl"))
Parameters:
-
*predicates(Predicate, default:()) –Zero or more
Predicateobjects (fromFieldRefcomparisons or manual construction). -
**kwargs(object, default:{}) –Field names (with optional operator suffix) mapped to the value(s) to compare against.
Returns:
-
Self–A new query with the additional predicates applied.
Source code in src/horde_model_reference/query.py
where_classification
where_classification(
*,
domain: MODEL_DOMAIN | None = None,
purpose: MODEL_PURPOSE | None = None,
) -> Self
Filter records by their model_classification.
Source code in src/horde_model_reference/query.py
tags_any
Keep records whose tags field contains any of tags.
Source code in src/horde_model_reference/query.py
tags_all
Keep records whose tags field contains all of tags.
Source code in src/horde_model_reference/query.py
tags_none
Exclude records whose tags field contains any of tags.
Source code in src/horde_model_reference/query.py
filter
order_by
Sort results by field; raises ValueError if values are not comparable.
field may be a field-name string, a typed
:class:~horde_model_reference.query_fields.FieldRef from the field DSL
(e.g. ImageFields.size_on_disk_bytes), or an OrderSpec
(e.g. ImageFields.size_on_disk_bytes.desc()). A bare string or FieldRef sorts
ascending unless descending=True; an OrderSpec already carries its own direction
(passing descending alongside one has no effect).
Source code in src/horde_model_reference/query.py
where_source
Keep only records originating from one of sources.
When the query has no per-record provenance (canonical-only), every record
is treated as coming from :data:~horde_model_reference.source_consts.HORDE_SOURCE_ID.
Parameters:
-
*sources(str, default:()) –One or more source ids to keep.
Returns:
-
Self–A new query restricted to the given sources.
Source code in src/horde_model_reference/query.py
limit
offset
_filtered_pairs
Return (record, source) pairs after applying record + source predicates.
No de-duplication, sorting, or pagination is performed. When the query has
no provenance, every source is :data:HORDE_SOURCE_ID.
Source code in src/horde_model_reference/query.py
_execute_with_sources
Apply predicates, canonical-wins de-duplication, sorting, and pagination.
Returns the surviving records and their aligned source ids. De-duplication keeps the first occurrence of each model name; because the manager supplies records canonical-first, the canonical source wins collisions by default.
Source code in src/horde_model_reference/query.py
_execute
Apply all predicates, sorting, and pagination, returning records only.
to_list
to_list_with_source
Execute the query and return (record, source_id) tuples.
sources
Return the source ids aligned with :meth:to_list (same order/length).
group_by_source
Group matching records by their source id.
Returns:
-
dict[str, list[T]]–A dict mapping each source id to the list of records from that source,
-
dict[str, list[T]]–after de-duplication/sorting/pagination.
Source code in src/horde_model_reference/query.py
duplicate_names
Return model names served by more than one source (collision detection).
Reflects the records remaining after filtering but before canonical-wins
de-duplication, so it surfaces exactly which names collided and which sources
supplied them. The first source listed for each name is the one that wins in
:meth:to_list.
Returns:
-
dict[str, list[str]]–A dict mapping each colliding model name to the list of source ids that
-
dict[str, list[str]]–supplied it (in priority order). Empty when there are no collisions.
Source code in src/horde_model_reference/query.py
has_duplicate_names
Return whether any model name was supplied by more than one source.
Source code in src/horde_model_reference/query.py
source_status
Return the per-source outcome of the read that built this query.
Maps each selected source id (including "horde") to "ok" (it
contributed at least one record), "empty" (it was reachable but had
nothing for this category), or "error" (it raised during fetch and was
skipped). This distinguishes a provider that failed from one that was
merely empty - both are otherwise silently absent from a merged read.
For a canonical-only query (the default source="horde"), the map is
derived from whether any record is present, so the method is always
answerable regardless of how the query was constructed.
Returns:
-
dict[str, SourceOutcome]–A dict mapping source id to its outcome.
Source code in src/horde_model_reference/query.py
failed_sources
Return the selected source ids that raised during fetch (status "error").
Sugar over :meth:source_status; check this before trusting a merged read if
a missing provider would be a problem for you.
Returns:
Source code in src/horde_model_reference/query.py
first
count
distinct
Return unique values of field across matching records (raises on unhashable values).
field may be a field-name string or a typed FieldRef from the field DSL.
Source code in src/horde_model_reference/query.py
group_by
Group matching records by field value.
field may be a field-name string or a typed FieldRef from the field DSL.
Returns:
-
dict[Hashable, list[T]]–A dict mapping each distinct value to the list of records with that value.
Source code in src/horde_model_reference/query.py
_parse_key
staticmethod
Split field__op into (field, op) or (field, None).
Source code in src/horde_model_reference/query.py
_eq_predicate
staticmethod
Build an equality predicate for field_name.
Source code in src/horde_model_reference/query.py
_cmp_predicate
staticmethod
_cmp_predicate(
field_name: str, op_name: str, value: object
) -> Callable[[GenericModelRecord], bool]
Build a comparison predicate for field_name using op_name.
Source code in src/horde_model_reference/query.py
ImageGenerationQuery
Bases: ModelQuery[ImageGenerationModelRecord, ImageGenFieldName]
Query builder with image-generation-specific helpers.
Adds typed convenience methods for common image model filters
(baseline, NSFW, inpainting) and overloaded field-name parameters
that give IDE autocomplete for ImageGenerationModelRecord fields.
Source code in src/horde_model_reference/query.py
_predicates
instance-attribute
_sources
instance-attribute
_source_predicates
instance-attribute
_source_predicates: Sequence[Callable[[str], bool]] = (
list(source_predicates) if source_predicates else []
)
_source_status
instance-attribute
_source_status: dict[str, SourceOutcome] | None = (
dict(source_status)
if source_status is not None
else None
)
for_baseline
Keep only models with the given baseline.
Source code in src/horde_model_reference/query.py
only_nsfw
exclude_nsfw
only_inpainting
Keep only inpainting models.
exclude_inpainting
Remove inpainting models.
__init__
__init__(
records: Sequence[T],
record_type: type[GenericModelRecord],
*,
predicates: Sequence[Callable[..., bool]] | None = None,
sort_key: str | None = None,
sort_descending: bool = False,
offset_value: int = 0,
limit_value: int | None = None,
sources: Sequence[str] | None = None,
source_predicates: Sequence[Callable[[str], bool]]
| None = None,
source_status: Mapping[str, SourceOutcome]
| None = None,
) -> None
Source code in src/horde_model_reference/query.py
_clone
_clone(
records: Sequence[T] | None = None,
record_type: type[GenericModelRecord] | None = None,
predicates: Sequence[Callable[..., bool]] | None = None,
sort_key: str | None = None,
sort_descending: bool | None = None,
offset_value: int | None = None,
limit_value: int | None = None,
source_predicates: Sequence[Callable[[str], bool]]
| None = None,
) -> Self
Create a shallow copy with optional overrides.
Uses type(self) so that subclasses (TextModelQuery,
ImageGenerationQuery, etc.) automatically get back their own
concrete type without needing to override this method.
_records, _sources and _source_status are passed through unchanged
(fluent methods only ever adjust predicates/sort/pagination), so the records
stay aligned with their provenance and the per-source outcome map is preserved.
Source code in src/horde_model_reference/query.py
where
Filter records by field equality, comparison operators, or Predicate objects.
Supports three styles that can be freely mixed in one call:
- Keyword equality/comparison (Django-style suffixes):
where(nsfw=False, size_on_disk_bytes__gt=1_000_000_000) - Field-ref predicates (typed DSL):
where(ImageFields.nsfw == false, ImageFields.size_on_disk_bytes > 1_000_000_000) - Composed predicates (boolean algebra):
where((ImageFields.nsfw == false) & (ImageFields.baseline == "stable_diffusion_xl"))
Parameters:
-
*predicates(Predicate, default:()) –Zero or more
Predicateobjects (fromFieldRefcomparisons or manual construction). -
**kwargs(object, default:{}) –Field names (with optional operator suffix) mapped to the value(s) to compare against.
Returns:
-
Self–A new query with the additional predicates applied.
Source code in src/horde_model_reference/query.py
where_classification
where_classification(
*,
domain: MODEL_DOMAIN | None = None,
purpose: MODEL_PURPOSE | None = None,
) -> Self
Filter records by their model_classification.
Source code in src/horde_model_reference/query.py
tags_any
Keep records whose tags field contains any of tags.
Source code in src/horde_model_reference/query.py
tags_all
Keep records whose tags field contains all of tags.
Source code in src/horde_model_reference/query.py
tags_none
Exclude records whose tags field contains any of tags.
Source code in src/horde_model_reference/query.py
filter
order_by
Sort results by field; raises ValueError if values are not comparable.
field may be a field-name string, a typed
:class:~horde_model_reference.query_fields.FieldRef from the field DSL
(e.g. ImageFields.size_on_disk_bytes), or an OrderSpec
(e.g. ImageFields.size_on_disk_bytes.desc()). A bare string or FieldRef sorts
ascending unless descending=True; an OrderSpec already carries its own direction
(passing descending alongside one has no effect).
Source code in src/horde_model_reference/query.py
where_source
Keep only records originating from one of sources.
When the query has no per-record provenance (canonical-only), every record
is treated as coming from :data:~horde_model_reference.source_consts.HORDE_SOURCE_ID.
Parameters:
-
*sources(str, default:()) –One or more source ids to keep.
Returns:
-
Self–A new query restricted to the given sources.
Source code in src/horde_model_reference/query.py
limit
offset
_filtered_pairs
Return (record, source) pairs after applying record + source predicates.
No de-duplication, sorting, or pagination is performed. When the query has
no provenance, every source is :data:HORDE_SOURCE_ID.
Source code in src/horde_model_reference/query.py
_execute_with_sources
Apply predicates, canonical-wins de-duplication, sorting, and pagination.
Returns the surviving records and their aligned source ids. De-duplication keeps the first occurrence of each model name; because the manager supplies records canonical-first, the canonical source wins collisions by default.
Source code in src/horde_model_reference/query.py
_execute
Apply all predicates, sorting, and pagination, returning records only.
to_list
to_list_with_source
Execute the query and return (record, source_id) tuples.
sources
Return the source ids aligned with :meth:to_list (same order/length).
group_by_source
Group matching records by their source id.
Returns:
-
dict[str, list[T]]–A dict mapping each source id to the list of records from that source,
-
dict[str, list[T]]–after de-duplication/sorting/pagination.
Source code in src/horde_model_reference/query.py
duplicate_names
Return model names served by more than one source (collision detection).
Reflects the records remaining after filtering but before canonical-wins
de-duplication, so it surfaces exactly which names collided and which sources
supplied them. The first source listed for each name is the one that wins in
:meth:to_list.
Returns:
-
dict[str, list[str]]–A dict mapping each colliding model name to the list of source ids that
-
dict[str, list[str]]–supplied it (in priority order). Empty when there are no collisions.
Source code in src/horde_model_reference/query.py
has_duplicate_names
Return whether any model name was supplied by more than one source.
Source code in src/horde_model_reference/query.py
source_status
Return the per-source outcome of the read that built this query.
Maps each selected source id (including "horde") to "ok" (it
contributed at least one record), "empty" (it was reachable but had
nothing for this category), or "error" (it raised during fetch and was
skipped). This distinguishes a provider that failed from one that was
merely empty - both are otherwise silently absent from a merged read.
For a canonical-only query (the default source="horde"), the map is
derived from whether any record is present, so the method is always
answerable regardless of how the query was constructed.
Returns:
-
dict[str, SourceOutcome]–A dict mapping source id to its outcome.
Source code in src/horde_model_reference/query.py
failed_sources
Return the selected source ids that raised during fetch (status "error").
Sugar over :meth:source_status; check this before trusting a merged read if
a missing provider would be a problem for you.
Returns:
Source code in src/horde_model_reference/query.py
first
count
distinct
Return unique values of field across matching records (raises on unhashable values).
field may be a field-name string or a typed FieldRef from the field DSL.
Source code in src/horde_model_reference/query.py
group_by
Group matching records by field value.
field may be a field-name string or a typed FieldRef from the field DSL.
Returns:
-
dict[Hashable, list[T]]–A dict mapping each distinct value to the list of records with that value.
Source code in src/horde_model_reference/query.py
_parse_key
staticmethod
Split field__op into (field, op) or (field, None).
Source code in src/horde_model_reference/query.py
_eq_predicate
staticmethod
Build an equality predicate for field_name.
Source code in src/horde_model_reference/query.py
_cmp_predicate
staticmethod
_cmp_predicate(
field_name: str, op_name: str, value: object
) -> Callable[[GenericModelRecord], bool]
Build a comparison predicate for field_name using op_name.
Source code in src/horde_model_reference/query.py
TextModelQuery
Bases: ModelQuery[TextGenerationModelRecord, TextGenFieldName]
Query builder with text-generation-specific helpers.
Adds filtering by backend prefix, quantization status, and grouping
by base model name. Every fluent method returns Self so the full
chain stays type-safe.
Source code in src/horde_model_reference/query.py
_predicates
instance-attribute
_sources
instance-attribute
_source_predicates
instance-attribute
_source_predicates: Sequence[Callable[[str], bool]] = (
list(source_predicates) if source_predicates else []
)
_source_status
instance-attribute
_source_status: dict[str, SourceOutcome] | None = (
dict(source_status)
if source_status is not None
else None
)
for_backend
Keep only models whose name starts with the legacy prefix for backend.
Source code in src/horde_model_reference/query.py
exclude_backend_variations
Remove models that carry any legacy backend prefix.
Source code in src/horde_model_reference/query.py
only_quantized
Keep only quantized model variants.
Source code in src/horde_model_reference/query.py
exclude_quantized
Remove quantized model variants.
Source code in src/horde_model_reference/query.py
group_by_base_model
Group matching records by their parsed base model name.
Returns:
-
dict[str, list[TextGenerationModelRecord]]–A dict mapping each base model name to the list of matching records.
Source code in src/horde_model_reference/query.py
__init__
__init__(
records: Sequence[T],
record_type: type[GenericModelRecord],
*,
predicates: Sequence[Callable[..., bool]] | None = None,
sort_key: str | None = None,
sort_descending: bool = False,
offset_value: int = 0,
limit_value: int | None = None,
sources: Sequence[str] | None = None,
source_predicates: Sequence[Callable[[str], bool]]
| None = None,
source_status: Mapping[str, SourceOutcome]
| None = None,
) -> None
Source code in src/horde_model_reference/query.py
_clone
_clone(
records: Sequence[T] | None = None,
record_type: type[GenericModelRecord] | None = None,
predicates: Sequence[Callable[..., bool]] | None = None,
sort_key: str | None = None,
sort_descending: bool | None = None,
offset_value: int | None = None,
limit_value: int | None = None,
source_predicates: Sequence[Callable[[str], bool]]
| None = None,
) -> Self
Create a shallow copy with optional overrides.
Uses type(self) so that subclasses (TextModelQuery,
ImageGenerationQuery, etc.) automatically get back their own
concrete type without needing to override this method.
_records, _sources and _source_status are passed through unchanged
(fluent methods only ever adjust predicates/sort/pagination), so the records
stay aligned with their provenance and the per-source outcome map is preserved.
Source code in src/horde_model_reference/query.py
where
Filter records by field equality, comparison operators, or Predicate objects.
Supports three styles that can be freely mixed in one call:
- Keyword equality/comparison (Django-style suffixes):
where(nsfw=False, size_on_disk_bytes__gt=1_000_000_000) - Field-ref predicates (typed DSL):
where(ImageFields.nsfw == false, ImageFields.size_on_disk_bytes > 1_000_000_000) - Composed predicates (boolean algebra):
where((ImageFields.nsfw == false) & (ImageFields.baseline == "stable_diffusion_xl"))
Parameters:
-
*predicates(Predicate, default:()) –Zero or more
Predicateobjects (fromFieldRefcomparisons or manual construction). -
**kwargs(object, default:{}) –Field names (with optional operator suffix) mapped to the value(s) to compare against.
Returns:
-
Self–A new query with the additional predicates applied.
Source code in src/horde_model_reference/query.py
where_classification
where_classification(
*,
domain: MODEL_DOMAIN | None = None,
purpose: MODEL_PURPOSE | None = None,
) -> Self
Filter records by their model_classification.
Source code in src/horde_model_reference/query.py
tags_any
Keep records whose tags field contains any of tags.
Source code in src/horde_model_reference/query.py
tags_all
Keep records whose tags field contains all of tags.
Source code in src/horde_model_reference/query.py
tags_none
Exclude records whose tags field contains any of tags.
Source code in src/horde_model_reference/query.py
filter
order_by
Sort results by field; raises ValueError if values are not comparable.
field may be a field-name string, a typed
:class:~horde_model_reference.query_fields.FieldRef from the field DSL
(e.g. ImageFields.size_on_disk_bytes), or an OrderSpec
(e.g. ImageFields.size_on_disk_bytes.desc()). A bare string or FieldRef sorts
ascending unless descending=True; an OrderSpec already carries its own direction
(passing descending alongside one has no effect).
Source code in src/horde_model_reference/query.py
where_source
Keep only records originating from one of sources.
When the query has no per-record provenance (canonical-only), every record
is treated as coming from :data:~horde_model_reference.source_consts.HORDE_SOURCE_ID.
Parameters:
-
*sources(str, default:()) –One or more source ids to keep.
Returns:
-
Self–A new query restricted to the given sources.
Source code in src/horde_model_reference/query.py
limit
offset
_filtered_pairs
Return (record, source) pairs after applying record + source predicates.
No de-duplication, sorting, or pagination is performed. When the query has
no provenance, every source is :data:HORDE_SOURCE_ID.
Source code in src/horde_model_reference/query.py
_execute_with_sources
Apply predicates, canonical-wins de-duplication, sorting, and pagination.
Returns the surviving records and their aligned source ids. De-duplication keeps the first occurrence of each model name; because the manager supplies records canonical-first, the canonical source wins collisions by default.
Source code in src/horde_model_reference/query.py
_execute
Apply all predicates, sorting, and pagination, returning records only.
to_list
to_list_with_source
Execute the query and return (record, source_id) tuples.
sources
Return the source ids aligned with :meth:to_list (same order/length).
group_by_source
Group matching records by their source id.
Returns:
-
dict[str, list[T]]–A dict mapping each source id to the list of records from that source,
-
dict[str, list[T]]–after de-duplication/sorting/pagination.
Source code in src/horde_model_reference/query.py
duplicate_names
Return model names served by more than one source (collision detection).
Reflects the records remaining after filtering but before canonical-wins
de-duplication, so it surfaces exactly which names collided and which sources
supplied them. The first source listed for each name is the one that wins in
:meth:to_list.
Returns:
-
dict[str, list[str]]–A dict mapping each colliding model name to the list of source ids that
-
dict[str, list[str]]–supplied it (in priority order). Empty when there are no collisions.
Source code in src/horde_model_reference/query.py
has_duplicate_names
Return whether any model name was supplied by more than one source.
Source code in src/horde_model_reference/query.py
source_status
Return the per-source outcome of the read that built this query.
Maps each selected source id (including "horde") to "ok" (it
contributed at least one record), "empty" (it was reachable but had
nothing for this category), or "error" (it raised during fetch and was
skipped). This distinguishes a provider that failed from one that was
merely empty - both are otherwise silently absent from a merged read.
For a canonical-only query (the default source="horde"), the map is
derived from whether any record is present, so the method is always
answerable regardless of how the query was constructed.
Returns:
-
dict[str, SourceOutcome]–A dict mapping source id to its outcome.
Source code in src/horde_model_reference/query.py
failed_sources
Return the selected source ids that raised during fetch (status "error").
Sugar over :meth:source_status; check this before trusting a merged read if
a missing provider would be a problem for you.
Returns:
Source code in src/horde_model_reference/query.py
first
count
distinct
Return unique values of field across matching records (raises on unhashable values).
field may be a field-name string or a typed FieldRef from the field DSL.
Source code in src/horde_model_reference/query.py
group_by
Group matching records by field value.
field may be a field-name string or a typed FieldRef from the field DSL.
Returns:
-
dict[Hashable, list[T]]–A dict mapping each distinct value to the list of records with that value.
Source code in src/horde_model_reference/query.py
_parse_key
staticmethod
Split field__op into (field, op) or (field, None).
Source code in src/horde_model_reference/query.py
_eq_predicate
staticmethod
Build an equality predicate for field_name.
Source code in src/horde_model_reference/query.py
_cmp_predicate
staticmethod
_cmp_predicate(
field_name: str, op_name: str, value: object
) -> Callable[[GenericModelRecord], bool]
Build a comparison predicate for field_name using op_name.
Source code in src/horde_model_reference/query.py
ControlNetQuery
Bases: ModelQuery[GenericModelRecord, ControlNetFieldName]
Query builder for ControlNet models.
Adds typed convenience methods for filtering by ControlNet style and grouping by
it. Every fluent method returns Self so the full chain stays type-safe.
Source code in src/horde_model_reference/query.py
_predicates
instance-attribute
_sources
instance-attribute
_source_predicates
instance-attribute
_source_predicates: Sequence[Callable[[str], bool]] = (
list(source_predicates) if source_predicates else []
)
_source_status
instance-attribute
_source_status: dict[str, SourceOutcome] | None = (
dict(source_status)
if source_status is not None
else None
)
for_style
Keep only ControlNet models with the given style.
Source code in src/horde_model_reference/query.py
group_by_style
Group matching records by their ControlNet style.
Returns:
-
dict[str, list[GenericModelRecord]]–A dict mapping each style to the list of matching records.
Source code in src/horde_model_reference/query.py
__init__
__init__(
records: Sequence[T],
record_type: type[GenericModelRecord],
*,
predicates: Sequence[Callable[..., bool]] | None = None,
sort_key: str | None = None,
sort_descending: bool = False,
offset_value: int = 0,
limit_value: int | None = None,
sources: Sequence[str] | None = None,
source_predicates: Sequence[Callable[[str], bool]]
| None = None,
source_status: Mapping[str, SourceOutcome]
| None = None,
) -> None
Source code in src/horde_model_reference/query.py
_clone
_clone(
records: Sequence[T] | None = None,
record_type: type[GenericModelRecord] | None = None,
predicates: Sequence[Callable[..., bool]] | None = None,
sort_key: str | None = None,
sort_descending: bool | None = None,
offset_value: int | None = None,
limit_value: int | None = None,
source_predicates: Sequence[Callable[[str], bool]]
| None = None,
) -> Self
Create a shallow copy with optional overrides.
Uses type(self) so that subclasses (TextModelQuery,
ImageGenerationQuery, etc.) automatically get back their own
concrete type without needing to override this method.
_records, _sources and _source_status are passed through unchanged
(fluent methods only ever adjust predicates/sort/pagination), so the records
stay aligned with their provenance and the per-source outcome map is preserved.
Source code in src/horde_model_reference/query.py
where
Filter records by field equality, comparison operators, or Predicate objects.
Supports three styles that can be freely mixed in one call:
- Keyword equality/comparison (Django-style suffixes):
where(nsfw=False, size_on_disk_bytes__gt=1_000_000_000) - Field-ref predicates (typed DSL):
where(ImageFields.nsfw == false, ImageFields.size_on_disk_bytes > 1_000_000_000) - Composed predicates (boolean algebra):
where((ImageFields.nsfw == false) & (ImageFields.baseline == "stable_diffusion_xl"))
Parameters:
-
*predicates(Predicate, default:()) –Zero or more
Predicateobjects (fromFieldRefcomparisons or manual construction). -
**kwargs(object, default:{}) –Field names (with optional operator suffix) mapped to the value(s) to compare against.
Returns:
-
Self–A new query with the additional predicates applied.
Source code in src/horde_model_reference/query.py
where_classification
where_classification(
*,
domain: MODEL_DOMAIN | None = None,
purpose: MODEL_PURPOSE | None = None,
) -> Self
Filter records by their model_classification.
Source code in src/horde_model_reference/query.py
tags_any
Keep records whose tags field contains any of tags.
Source code in src/horde_model_reference/query.py
tags_all
Keep records whose tags field contains all of tags.
Source code in src/horde_model_reference/query.py
tags_none
Exclude records whose tags field contains any of tags.
Source code in src/horde_model_reference/query.py
filter
order_by
Sort results by field; raises ValueError if values are not comparable.
field may be a field-name string, a typed
:class:~horde_model_reference.query_fields.FieldRef from the field DSL
(e.g. ImageFields.size_on_disk_bytes), or an OrderSpec
(e.g. ImageFields.size_on_disk_bytes.desc()). A bare string or FieldRef sorts
ascending unless descending=True; an OrderSpec already carries its own direction
(passing descending alongside one has no effect).
Source code in src/horde_model_reference/query.py
where_source
Keep only records originating from one of sources.
When the query has no per-record provenance (canonical-only), every record
is treated as coming from :data:~horde_model_reference.source_consts.HORDE_SOURCE_ID.
Parameters:
-
*sources(str, default:()) –One or more source ids to keep.
Returns:
-
Self–A new query restricted to the given sources.
Source code in src/horde_model_reference/query.py
limit
offset
_filtered_pairs
Return (record, source) pairs after applying record + source predicates.
No de-duplication, sorting, or pagination is performed. When the query has
no provenance, every source is :data:HORDE_SOURCE_ID.
Source code in src/horde_model_reference/query.py
_execute_with_sources
Apply predicates, canonical-wins de-duplication, sorting, and pagination.
Returns the surviving records and their aligned source ids. De-duplication keeps the first occurrence of each model name; because the manager supplies records canonical-first, the canonical source wins collisions by default.
Source code in src/horde_model_reference/query.py
_execute
Apply all predicates, sorting, and pagination, returning records only.
to_list
to_list_with_source
Execute the query and return (record, source_id) tuples.
sources
Return the source ids aligned with :meth:to_list (same order/length).
group_by_source
Group matching records by their source id.
Returns:
-
dict[str, list[T]]–A dict mapping each source id to the list of records from that source,
-
dict[str, list[T]]–after de-duplication/sorting/pagination.
Source code in src/horde_model_reference/query.py
duplicate_names
Return model names served by more than one source (collision detection).
Reflects the records remaining after filtering but before canonical-wins
de-duplication, so it surfaces exactly which names collided and which sources
supplied them. The first source listed for each name is the one that wins in
:meth:to_list.
Returns:
-
dict[str, list[str]]–A dict mapping each colliding model name to the list of source ids that
-
dict[str, list[str]]–supplied it (in priority order). Empty when there are no collisions.
Source code in src/horde_model_reference/query.py
has_duplicate_names
Return whether any model name was supplied by more than one source.
Source code in src/horde_model_reference/query.py
source_status
Return the per-source outcome of the read that built this query.
Maps each selected source id (including "horde") to "ok" (it
contributed at least one record), "empty" (it was reachable but had
nothing for this category), or "error" (it raised during fetch and was
skipped). This distinguishes a provider that failed from one that was
merely empty - both are otherwise silently absent from a merged read.
For a canonical-only query (the default source="horde"), the map is
derived from whether any record is present, so the method is always
answerable regardless of how the query was constructed.
Returns:
-
dict[str, SourceOutcome]–A dict mapping source id to its outcome.
Source code in src/horde_model_reference/query.py
failed_sources
Return the selected source ids that raised during fetch (status "error").
Sugar over :meth:source_status; check this before trusting a merged read if
a missing provider would be a problem for you.
Returns:
Source code in src/horde_model_reference/query.py
first
count
distinct
Return unique values of field across matching records (raises on unhashable values).
field may be a field-name string or a typed FieldRef from the field DSL.
Source code in src/horde_model_reference/query.py
group_by
Group matching records by field value.
field may be a field-name string or a typed FieldRef from the field DSL.
Returns:
-
dict[Hashable, list[T]]–A dict mapping each distinct value to the list of records with that value.
Source code in src/horde_model_reference/query.py
_parse_key
staticmethod
Split field__op into (field, op) or (field, None).
Source code in src/horde_model_reference/query.py
_eq_predicate
staticmethod
Build an equality predicate for field_name.
Source code in src/horde_model_reference/query.py
_cmp_predicate
staticmethod
_cmp_predicate(
field_name: str, op_name: str, value: object
) -> Callable[[GenericModelRecord], bool]
Build a comparison predicate for field_name using op_name.
Source code in src/horde_model_reference/query.py
_resolve_field_value
Resolve a nested field path like finetune_series__name or raise on missing segments.
Source code in src/horde_model_reference/query.py
_validate_field_exists
Validate that field_name (top-level segment) exists on the Pydantic model.
This serves as the security boundary for user-supplied field names in sort, filter, and group-by operations - only fields declared on the Pydantic model are accepted.
Source code in src/horde_model_reference/query.py
_field_name
Resolve a typed :class:FieldRef (or a plain field-name string) to its field name.
Lets the field-accepting query methods (order_by, distinct, group_by) take a
FieldRef from the field DSL directly - not only a string - without each having to unwrap it.
Source code in src/horde_model_reference/query.py
_is_non_string_iterable
Return True when value is an iterable but not a string/bytes.
_to_hashable
Convert value into a hashable form or raise a helpful error.
Source code in src/horde_model_reference/query.py
build_query
build_query(
records: dict[str, T],
record_type: type[T],
*,
sources: Sequence[str] | None = None,
) -> ModelQuery[T, str]
Create a ModelQuery from a name-to-record mapping.
Parameters:
-
records(dict[str, T]) –The mapping returned by
ModelReferenceManager.get_model_reference(). -
record_type(type[T]) –The Pydantic record type for field validation.
-
sources(Sequence[str] | None, default:None) –Optional source ids aligned with
records.values()for provenance.
Returns:
-
ModelQuery[T, str]–A fresh
ModelQueryready for chaining.
Source code in src/horde_model_reference/query.py
build_image_query
build_image_query(
records: dict[str, ImageGenerationModelRecord],
*,
sources: Sequence[str] | None = None,
) -> ImageGenerationQuery
Create an ImageGenerationQuery from a name-to-record mapping.
Parameters:
-
records(dict[str, ImageGenerationModelRecord]) –The mapping returned by
ModelReferenceManager.get_model_reference()for theimage_generationcategory. -
sources(Sequence[str] | None, default:None) –Optional source ids aligned with
records.values()for provenance.
Returns:
-
ImageGenerationQuery–A fresh
ImageGenerationQueryready for chaining.
Source code in src/horde_model_reference/query.py
build_text_query
build_text_query(
records: dict[str, TextGenerationModelRecord],
*,
sources: Sequence[str] | None = None,
) -> TextModelQuery
Create a TextModelQuery from a name-to-record mapping.
Parameters:
-
records(dict[str, TextGenerationModelRecord]) –The mapping returned by
ModelReferenceManager.get_model_reference()for thetext_generationcategory. -
sources(Sequence[str] | None, default:None) –Optional source ids aligned with
records.values()for provenance.
Returns:
-
TextModelQuery–A fresh
TextModelQueryready for chaining.
Source code in src/horde_model_reference/query.py
build_controlnet_query
build_controlnet_query(
records: dict[str, ControlNetModelRecord],
*,
sources: Sequence[str] | None = None,
) -> ControlNetQuery
Create a ControlNetQuery from a name-to-record mapping.
Parameters:
-
records(dict[str, ControlNetModelRecord]) –The mapping returned by
ModelReferenceManager.get_model_reference()for thecontrolnetcategory. -
sources(Sequence[str] | None, default:None) –Optional source ids aligned with
records.values()for provenance.
Returns:
-
ControlNetQuery–A fresh
ControlNetQueryready for chaining.
Source code in src/horde_model_reference/query.py
build_cross_category_query
build_cross_category_query(
all_references: dict[
MODEL_REFERENCE_CATEGORY,
dict[str, GenericModelRecord],
],
) -> ModelQuery[GenericModelRecord, str]
Create a ModelQuery spanning all categories.
Parameters:
-
all_references(dict[MODEL_REFERENCE_CATEGORY, dict[str, GenericModelRecord]]) –Mapping returned by
ModelReferenceManager.get_all_model_references().
Returns:
-
ModelQuery[GenericModelRecord, str]–A
ModelQuery[GenericModelRecord]over every record in every category.