PostFetch¶
Helper for attaching related rows to a list of base objects after the base query has run. See the PostFetch guide for the join model, performance characteristics, and view integration.
PostFetch ¶
PostFetch(
queryset: Any,
to_attr: str,
values: list[str],
values_dict: dict[str, Any] | None = None,
limit: int | None = 1,
order_by: list[str] | None = None,
**queries: str,
)
Attaches related data to a list of base objects after they have been fetched or paginated. Useful when prefetch_related cannot be used.
post_fetch = PostFetch(
queryset=Content.objects.all(),
to_attr="content_data",
limit=1,
order_by=("-created_at",),
values=["id", "title", "created_at"],
content_id="content_ptr_id",
)
enriched = post_fetch.fetch(base_items)
Use afetch in async views.
Configure the post-fetch.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
queryset
|
Any
|
Secondary queryset to retrieve data from. |
required |
to_attr
|
str
|
Attribute or dict key under which the matched objects are attached on each base item. |
required |
values
|
list[str]
|
Field names retrieved via |
required |
values_dict
|
dict[str, Any] | None
|
Annotated value expressions passed as
|
None
|
limit
|
int | None
|
1 attaches the first match (or None when missing). An integer greater than 1 attaches a list of up to that many matches. None attaches all matches. |
1
|
order_by
|
list[str] | None
|
Fields applied to the secondary queryset before grouping. |
None
|
**queries
|
str
|
Mapping of secondary_field -> base_field. Each
base item's |
{}
|
get_value
staticmethod
¶
Returns the named attribute or dict key from a base item.
build_key_tuple ¶
Returns a tuple of join values for an item, or None if any join field is missing.
build_filter_kwargs ¶
Returns the secondary_field__in lookup map used to fetch related rows.
fetch ¶
Attaches matching secondary rows to each base item and returns the list. The base sequence is materialized once so repeated iteration does not re-execute the queryset.
afetch
async
¶
Async equivalent of fetch, iterating the secondary queryset with async for. The base sequence is materialized once.