fetch_modes.py 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. from django.core.exceptions import FieldFetchBlocked
  2. class FetchMode:
  3. __slots__ = ()
  4. track_peers = False
  5. def fetch(self, fetcher, instance):
  6. raise NotImplementedError("Subclasses must implement this method.")
  7. class FetchOne(FetchMode):
  8. __slots__ = ()
  9. def fetch(self, fetcher, instance):
  10. fetcher.fetch_one(instance)
  11. def __reduce__(self):
  12. return "FETCH_ONE"
  13. FETCH_ONE = FetchOne()
  14. class FetchPeers(FetchMode):
  15. __slots__ = ()
  16. track_peers = True
  17. def fetch(self, fetcher, instance):
  18. instances = [
  19. peer
  20. for peer_weakref in instance._state.peers
  21. if (peer := peer_weakref()) is not None
  22. ]
  23. if len(instances) > 1:
  24. fetcher.fetch_many(instances)
  25. else:
  26. fetcher.fetch_one(instance)
  27. def __reduce__(self):
  28. return "FETCH_PEERS"
  29. FETCH_PEERS = FetchPeers()
  30. class FetchRaise(FetchMode):
  31. __slots__ = ()
  32. def fetch(self, fetcher, instance):
  33. klass = instance.__class__.__qualname__
  34. field_name = fetcher.field.name
  35. raise FieldFetchBlocked(f"Fetching of {klass}.{field_name} blocked.") from None
  36. def __reduce__(self):
  37. return "FETCH_RAISE"
  38. FETCH_RAISE = FetchRaise()