Skip to content

Commit

Permalink
Use a DataLoader to efficiently batch load homeworlds
Browse files Browse the repository at this point in the history
See graphql-python#12 for background.
  • Loading branch information
Simon Willison committed Jul 10, 2017
1 parent 9d6ba16 commit cea0451
Showing 1 changed file with 13 additions and 0 deletions.
13 changes: 13 additions & 0 deletions starwars/schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,16 @@

import models

from promise import Promise
from promise.dataloader import DataLoader


class PlanetLoader(DataLoader):
def batch_load_fn(self, keys):
return Promise.resolve(models.Planet.objects.filter(pk__in=keys))

planet_loader = PlanetLoader()


def connection_for_type(_type):
class Connection(graphene.Connection):
Expand Down Expand Up @@ -94,6 +104,9 @@ def resolve_hair_colors(self):
def resolve_skin_colors(self):
return [c.strip() for c in self.skin_colors.split(',')]

def resolve_homeworld(self, *args):
return planet_loader.load(self.id)

class Meta:
model = models.Species
interfaces = (Node, )
Expand Down

0 comments on commit cea0451

Please sign in to comment.