only prefetch groups if detailed serialization was queried
This commit is contained in:
parent
37d95700d3
commit
4d544610e5
2 changed files with 15 additions and 12 deletions
|
@ -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())
|
||||
|
|
|
@ -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
|
||||
|
||||
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue