From d9a451765c62bfb1d61abe766e042d5a8f8ecb04 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Laura=20Kl=C3=BCnder?= Date: Fri, 12 May 2017 13:21:41 +0200 Subject: [PATCH] add ?detailed to Location API --- src/c3nav/mapdata/api.py | 5 +++-- src/c3nav/mapdata/models/locations.py | 9 +++++++++ 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/src/c3nav/mapdata/api.py b/src/c3nav/mapdata/api.py index 6b57e28b..eda47106 100644 --- a/src/c3nav/mapdata/api.py +++ b/src/c3nav/mapdata/api.py @@ -138,6 +138,7 @@ class LocationGroupViewSet(MapdataViewSet): class LocationViewSet(RetrieveModelMixin, GenericViewSet): """ only accesses locations that have can_search or can_describe set to true. + add ?detailed=1 to show all attributes. /{id}/ add ?show_redirect=1 to suppress redirects and show them as JSON. /search/ only accesses locations that have can_search set to true. Add GET Parameter ā€œsā€ to search. """ @@ -147,7 +148,7 @@ class LocationViewSet(RetrieveModelMixin, GenericViewSet): def list(self, request, *args, **kwargs): queryset = sorted(chain(*(model.objects.filter(Q(can_search=True) | Q(can_describe=True)) for model in LOCATION_MODELS)), key=lambda obj: obj.id) - return Response([obj.serialize(include_type=True) for obj in queryset]) + return Response([obj.serialize(include_type=True, detailed='detailed' in request.GET) for obj in queryset]) def retrieve(self, request, slug=None, *args, **kwargs): result = Location.get_by_slug(slug, self.get_queryset()) @@ -157,7 +158,7 @@ class LocationViewSet(RetrieveModelMixin, GenericViewSet): if 'show_redirects' in request.GET: return Response(result.serialize(include_type=True)) return redirect('../'+result.target.slug) # todo: why does redirect/reverse not work here? - return Response(result.get_child().serialize(include_type=True)) + return Response(result.get_child().serialize(include_type=True, detailed='detailed' in request.GET)) @list_route(methods=['get']) def types(self, request): diff --git a/src/c3nav/mapdata/models/locations.py b/src/c3nav/mapdata/models/locations.py index 5e104053..d711688e 100644 --- a/src/c3nav/mapdata/models/locations.py +++ b/src/c3nav/mapdata/models/locations.py @@ -1,3 +1,5 @@ +from collections import OrderedDict + import numpy as np from django.apps import apps from django.core.cache import cache @@ -58,6 +60,13 @@ class Location(LocationSlug, EditorFormMixin, models.Model): class Meta: abstract = True + def serialize(self, detailed=True, **kwargs): + result = super().serialize(**kwargs) + if not detailed: + for key in set(result.keys()) - {'type', 'id', 'slug', 'title', 'target'}: + result.pop(key) + return result + def _serialize(self, **kwargs): result = super()._serialize(**kwargs) result['titles'] = self.titles