summaryrefslogtreecommitdiff
path: root/django/db/models/fetch_modes.py
blob: 2b5e6aa212ddf5660392d2ec9531cc7cc865d7a0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
from django.core.exceptions import FieldFetchBlocked


class FetchMode:
    __slots__ = ()

    track_peers = False

    def fetch(self, fetcher, instance):
        raise NotImplementedError("Subclasses must implement this method.")


class FetchOne(FetchMode):
    __slots__ = ()

    def fetch(self, fetcher, instance):
        fetcher.fetch_one(instance)

    def __reduce__(self):
        return "FETCH_ONE"


FETCH_ONE = FetchOne()


class FetchPeers(FetchMode):
    __slots__ = ()

    track_peers = True

    def fetch(self, fetcher, instance):
        instances = [
            peer
            for peer_weakref in instance._state.peers
            if (peer := peer_weakref()) is not None
        ]
        if len(instances) > 1:
            fetcher.fetch_many(instances)
        else:
            fetcher.fetch_one(instance)

    def __reduce__(self):
        return "FETCH_PEERS"


FETCH_PEERS = FetchPeers()


class Raise(FetchMode):
    __slots__ = ()

    def fetch(self, fetcher, instance):
        klass = instance.__class__.__qualname__
        field_name = fetcher.field.name
        raise FieldFetchBlocked(f"Fetching of {klass}.{field_name} blocked.") from None

    def __reduce__(self):
        return "RAISE"


RAISE = Raise()