Improve dataloader doc

Explicitly mention that loaded values must have the same order as the
given keys
This commit is contained in:
Elias Tandel Barrionovo 2018-10-22 11:28:26 -03:00
parent 705cad76b2
commit 21dbaa93c4

View File

@ -25,8 +25,8 @@ Create loaders by providing a batch loading function.
return Promise.resolve([get_user(id=key) for key in keys])
A batch loading function accepts an list of keys, and returns a ``Promise``
which resolves to an list of ``values``.
A batch loading function accepts a list of keys, and returns a ``Promise``
which resolves to a list of ``values``.
Then load individual values from the loader. ``DataLoader`` will coalesce all
individual loads which occur within a single frame of execution (executed once
@ -34,7 +34,6 @@ the wrapping promise is resolved) and then call your batch function with all
requested keys.
.. code:: python
user_loader = UserLoader()
@ -47,6 +46,19 @@ requested keys.
A naive application may have issued *four* round-trips to a backend for the
required information, but with ``DataLoader`` this application will make at most *two*.
Note that loaded values are one-to-one with the keys and must have the same
order. This means that if you load all values from a single query, you must
make sure that you then order the query result for the results to match the keys:
.. code:: python
class UserLoader(DataLoader):
def batch_load_fn(self, keys):
users = {user.id: user for user in User.objects.filter(id__in=keys)}
return Promise.resolve([users.get(user_id) for user_id in keys])
``DataLoader`` allows you to decouple unrelated parts of your application without
sacrificing the performance of batch data-loading. While the loader presents
an API that loads individual values, all concurrent requests will be coalesced