From 4d544610e5d3a6735c40ab12813cb528b86efd21 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Laura=20Kl=C3=BCnder?= Date: Thu, 22 Jun 2017 19:53:25 +0200 Subject: [PATCH] only prefetch groups if detailed serialization was queried --- src/c3nav/mapdata/api.py | 18 ++++++++++-------- src/c3nav/mapdata/models/locations.py | 9 +++++---- 2 files changed, 15 insertions(+), 12 deletions(-) diff --git a/src/c3nav/mapdata/api.py b/src/c3nav/mapdata/api.py index 444bc7c4..de9b039c 100644 --- a/src/c3nav/mapdata/api.py +++ b/src/c3nav/mapdata/api.py @@ -154,17 +154,19 @@ class LocationViewSet(RetrieveModelMixin, GenericViewSet): lookup_field = 'slug' def list(self, request, *args, **kwargs): - queryset = self.get_queryset() + detailed = 'detailed' in request.GET + + queryset = self.get_queryset().order_by('id') queryset = queryset.filter(reduce(operator.or_, (Q(**{model._meta.default_related_name+'__isnull': False}) for model in get_submodels(Location)))) - for model in get_submodels(Location): - if model == LocationGroup: - continue - queryset = queryset.prefetch_related(Prefetch(model._meta.default_related_name+'__groups', - queryset=LocationGroup.objects.only('id', 'titles'))) + if detailed: + for model in get_submodels(Location): + if model == LocationGroup: + continue + queryset = queryset.prefetch_related(Prefetch(model._meta.default_related_name+'__groups', + queryset=LocationGroup.objects.only('id', 'titles'))) - return Response([obj.get_child().serialize(include_type=True, detailed='detailed' in request.GET) - for obj in queryset]) + return Response([obj.get_child().serialize(include_type=True, detailed=detailed) for obj in queryset]) def retrieve(self, request, slug=None, *args, **kwargs): result = Location.get_by_slug(slug, self.get_queryset()) diff --git a/src/c3nav/mapdata/models/locations.py b/src/c3nav/mapdata/models/locations.py index d0540da7..d2588798 100644 --- a/src/c3nav/mapdata/models/locations.py +++ b/src/c3nav/mapdata/models/locations.py @@ -68,7 +68,7 @@ class Location(LocationSlug, SerializableMixin, models.Model): self.titles = self.titles.copy() def serialize(self, detailed=True, **kwargs): - result = super().serialize(**kwargs) + result = super().serialize(detailed=detailed, **kwargs) if not detailed: for key in set(result.keys()) - {'type', 'id', 'slug', 'title', 'target'}: result.pop(key) @@ -150,9 +150,10 @@ class SpecificLocation(Location, models.Model): class Meta: abstract = True - def _serialize(self, **kwargs): - result = super()._serialize(**kwargs) - result['groups'] = list(g.pk for g in self.groups.all()) + def _serialize(self, detailed=True, **kwargs): + result = super()._serialize(detailed=detailed, **kwargs) + if detailed: + result['groups'] = list(g.pk for g in self.groups.all()) return result