from itertools import groupby from django.shortcuts import render from rest_framework.views import APIView from rest_framework.response import Response from .serializers import * from .models import * # Create your views here. class SafetyFileAPIView(APIView): def get(self, request): all_file = SafetyFile.objects.all() serializer_for_file = SafetyFileSerializer(instance=all_file, many=True) data = [] for (chapter_id, chapter_name), row in groupby(serializer_for_file.data, lambda x: (x['chapter_id'], x['chapter_name'])): chapter = { 'id': chapter_id, 'name': chapter_name, 'categories': [] } data.append(chapter) for (category_id, category_name), files in groupby(row, lambda x: (x['category_id'], x['category_name'])): chapter['categories'].append({ 'id': category_id, 'name': category_name, 'files': [file for file in files] }) return Response(data)