Skip to content

prefetch

Prefetch attaches a queryset to a prefetched relation, so the related models are filtered, ordered and narrowed to selected fields while they are loaded::

Text Only
1
2
3
Author.objects.prefetch_related(
    Prefetch("books", queryset=Book.objects.filter(year__gte=2000))
)

Prefetch dataclass

A relation to prefetch together with the queryset its models are loaded with.

Attributes:

Name Type Description
relation str

relation path, the same __ separated string prefetch_related accepts

queryset QuerySet[Any]

queryset of the related model; its filters, excludes, ordering and fields / exclude_fields apply to the prefetched models

Source code in ormar/queryset/prefetch.py
Python
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
@dataclass(frozen=True)
class Prefetch:
    """
    A relation to prefetch together with the queryset its models are loaded
    with.

    :ivar relation: relation path, the same ``__`` separated string
        ``prefetch_related`` accepts
    :ivar queryset: queryset of the related model; its filters, excludes,
        ordering and ``fields`` / ``exclude_fields`` apply to the prefetched
        models
    """

    relation: str
    queryset: "QuerySet[Any]"