@@ -25,16 +25,15 @@ Create loaders by providing a batch loading function.
25
25
return Promise.resolve([get_user(id = key) for key in keys])
26
26
27
27
28
- A batch loading function accepts an list of keys, and returns a ``Promise ``
29
- which resolves to an list of ``values ``.
28
+ A batch loading function accepts a list of keys, and returns a ``Promise ``
29
+ which resolves to a list of ``values ``.
30
30
31
31
Then load individual values from the loader. ``DataLoader `` will coalesce all
32
32
individual loads which occur within a single frame of execution (executed once
33
33
the wrapping promise is resolved) and then call your batch function with all
34
34
requested keys.
35
35
36
36
37
-
38
37
.. code :: python
39
38
40
39
user_loader = UserLoader()
@@ -47,6 +46,19 @@ requested keys.
47
46
A naive application may have issued *four * round-trips to a backend for the
48
47
required information, but with ``DataLoader `` this application will make at most *two *.
49
48
49
+ Note that loaded values are one-to-one with the keys and must have the same
50
+ order. This means that if you load all values from a single query, you must
51
+ make sure that you then order the query result for the results to match the keys:
52
+
53
+
54
+ .. code :: python
55
+
56
+ class UserLoader (DataLoader ):
57
+ def batch_load_fn (self , keys ):
58
+ users = {user.id: user for user in User.objects.filter(id__in = keys)}
59
+ return Promise.resolve([users.get(user_id) for user_id in keys])
60
+
61
+
50
62
``DataLoader `` allows you to decouple unrelated parts of your application without
51
63
sacrificing the performance of batch data-loading. While the loader presents
52
64
an API that loads individual values, all concurrent requests will be coalesced
0 commit comments