improve querys on mapdata API /locations/
import mimetypes
+import operator
+from functools import reduce
from itertools import chain
from django.db.models import Prefetch, Q
@@ -152,9 +154,17 @@ class LocationViewSet(RetrieveModelMixin, GenericViewSet):
lookup_field = 'slug'
def list(self, request, *args, **kwargs):
- queryset = sorted(chain(*(optimize_query(model.objects.filter(Q(can_search=True) | Q(can_describe=True)))
- for model in get_submodels(Location))), key=lambda obj: obj.id)
- return Response([obj.serialize(include_type=True, detailed='detailed' in request.GET) for obj in queryset])
+ queryset = self.get_queryset()
+ 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')))
+
+ return Response([obj.get_child().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())
