I have data inside postgres database like this
and I want to create rest api to return nested json like this
[
{
"machine": "MC1",
"work" : [
{
"title": "21TCE20200910",
"subTitle1": "INSERT CORE",
"subTitle2": "P20200910-001",
"subTitle3": "DRAW20200910",
"status": 0,
"delay": 2
},
{
"title": "21TCE20200910",
"subTitle1": "INSERT CORE",
"subTitle2": "P20200910-001",
"subTitle3": "DRAW20200912",
"status": 1,
"delay": 1
}
]
},
{
"machine": "MC2",
"work" : [
{
"title": "21TCE20200911",
"subTitle1": "SCREW",
"subTitle2": "P20200910-001",
"subTitle3": "DRAW20200910",
"status": 1,
"delay": 2
}
]
},
{
"machine": "MC3",
"work" : [
{
"title": "21TCE20200913",
"subTitle1": "INSERT FIX",
"subTitle2": "P20200910-001",
"subTitle3": "DRAW20200910",
"status": 0,
"delay": 1
}
]
}
]
Currently I can only return normal json for each record but I want to group and return nested json like above any help would be appreciate
these below are my codes model.py
from django.db import models class MachineSchedule(models.Model): machine = models.CharField(max_length=255) title = models.CharField(max_length=255) subTitle1 = models.CharField(max_length=255) subTitle2 = models.CharField(max_length=255) subTitle3 = models.CharField(max_length=255) status = models.IntegerField(1) delay = models.IntegerField(1)
views.py
from django.shortcuts import render from rest_framework import generics from .models import MachineSchedule from .serializers import MachineScheduleSerializer class MachineScheduleListAPIView(generics.ListCreateAPIView): serializer_class = MachineScheduleSerializer model = MachineSchedule fields = '__all__'
serializers.py
from rest_framework import serializers from .models import MachineAllocate class MachineAllocateSerializer(serializers.ModelSerializer): class Meta: model = MachineAllocate fields = '__all__'