Skip to content

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 qs.values(*values). Copied per fetch call; safe to share between instances.

required
values_dict dict[str, Any] | None

Annotated value expressions passed as qs.values(**values_dict). For example {"upper_name": Upper("name")}.

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 base_field is collected and the secondary queryset is filtered with secondary_field__in=[...].

{}

get_value staticmethod

get_value(obj, attr, default=None)

Returns the named attribute or dict key from a base item.

build_key_tuple

build_key_tuple(obj, field_mapping)

Returns a tuple of join values for an item, or None if any join field is missing.

build_filter_kwargs

build_filter_kwargs(base_queryset)

Returns the secondary_field__in lookup map used to fetch related rows.

fetch

fetch(base_queryset)

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

afetch(base_queryset)

Async equivalent of fetch, iterating the secondary queryset with async for. The base sequence is materialized once.