show group categories in api
This commit is contained in:
parent
782666bcaf
commit
3762ebf37d
3 changed files with 13 additions and 7 deletions
|
@ -23,7 +23,8 @@ from c3nav.mapdata.utils.models import get_submodels
|
|||
|
||||
def optimize_query(qs):
|
||||
if issubclass(qs.model, SpecificLocation):
|
||||
qs = qs.prefetch_related(Prefetch('groups', queryset=LocationGroup.objects.only('id')))
|
||||
base_qs = LocationGroup.objects.select_related('category').only('id', 'titles', 'category')
|
||||
qs = qs.prefetch_related(Prefetch('groups', queryset=base_qs))
|
||||
return qs
|
||||
|
||||
|
||||
|
@ -170,9 +171,10 @@ class LocationViewSet(RetrieveModelMixin, GenericViewSet):
|
|||
queryset = queryset.filter(reduce(operator.or_, conditions))
|
||||
|
||||
if detailed:
|
||||
base_qs = LocationGroup.objects.all().select_related('category')
|
||||
for model in get_submodels(SpecificLocation):
|
||||
queryset = queryset.prefetch_related(Prefetch(model._meta.default_related_name + '__groups',
|
||||
queryset=LocationGroup.objects.only('id', 'titles')))
|
||||
queryset=base_qs))
|
||||
|
||||
return queryset
|
||||
|
||||
|
|
|
@ -144,7 +144,10 @@ class SpecificLocation(Location, models.Model):
|
|||
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())
|
||||
groups = {}
|
||||
for group in self.groups.all():
|
||||
groups.setdefault(group.category.name, []).append(group.pk)
|
||||
result['groups'] = groups
|
||||
return result
|
||||
|
||||
|
||||
|
|
|
@ -2,17 +2,18 @@ import json
|
|||
from collections import OrderedDict
|
||||
|
||||
|
||||
def _preencode(data, magic_marker, in_coords=False):
|
||||
def _preencode(data, magic_marker, in_coords=False, in_groups=False):
|
||||
if isinstance(data, dict):
|
||||
data = data.copy()
|
||||
for name, value in tuple(data.items()):
|
||||
if name in ('bounds', 'groups'):
|
||||
if name == 'bounds':
|
||||
data[name] = magic_marker+json.dumps(value)+magic_marker
|
||||
else:
|
||||
data[name] = _preencode(value, magic_marker, in_coords=(name == 'coordinates'))
|
||||
data[name] = _preencode(value, magic_marker,
|
||||
in_coords=(name == 'coordinates'), in_groups=(name == 'groups'))
|
||||
return data
|
||||
elif isinstance(data, (tuple, list)):
|
||||
if in_coords and len(data) == 2 and isinstance(data[0], (int, float)) and isinstance(data[1], (int, float)):
|
||||
if (in_coords and len(data) == 2) or in_groups:
|
||||
return magic_marker+json.dumps(data)+magic_marker
|
||||
else:
|
||||
return tuple(_preencode(value, magic_marker, in_coords) for value in data)
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue