Home > database >  Making a json structure with nested serializers concept
Making a json structure with nested serializers concept

Time:06-27

I'm trying to make an api with Django Rest Framework , the api format looks like this, I'm new to nested serializer concept so I've tried to make relational models and nested serializer that is available in the documentation but it doesn't work for me , is there anyone who can help ?

{
    "devices": {
        "device": [{
            "type": "MP",
            "time": "18/05/2022, 15:15:10",
            "MP_name": "MP1",
            "SN": "EMSMP001",
            "plant_name": "Greenaftech",
            "gatway_name": "gw1",
            "adress": 1,
            "baud_rate": 9600,
            "voltage": 230,
            "current": 10,
            "active_power": 2.3,
            "reactive_power": 0.01,
            "apparent_power": 2.3,
            "FP": 0.99,
            "frequency": 49.98
        },
        {
            "type": "TP",
            "time": "18/05/2022, 15:15:10",
            "TP_name": "TP1",
            "SN": "EMSMP002",
            "plant_name":"Greenaftech",
            "gatway_name":"gw1",
            "adress": 12,
            "baud_rate":1,
            "UA":1,
            "UB":1,
            "UC":1,
            "UAB":1,
            "UBC":1,
            "UAC":1,
            "IA":1,
            "IB":20,
            "IC":43,
            "frequency":11,
            "Pa":88,
            "Pb":30,
            "Pc":23,
            "Pt":42,
            "Qa":21,
            "Qb":31,
            "Qc":49,
            "Qt":82,
            "Sa":63,
            "Sb":83,
            "Sc":10,
            "St":39,
            "FPa":54,
            "FPb":43,
            "FPc":34,
            "FPt":87,
            "THDV":56,
            "THDI":74,
            "max_demand":2,
            "count_E":8,
            "count_Er":55
        },
        {
            "type": "VFD",
            "time": "18/05/2022, 15:15:10",
            "vfd_name": "VFD1",
            "SN": "EMSMP002",
            "plant_name":"plant1",
            "gatway_name":"gw3",
            "adress": 7,
            "baud_rate":1,
            "c00":8,
            "c01":8,
            "c02":8,
            "c03":8,
            "c04":8,
            "c06":8,
            "c07":8,
            "c12":8,
            "c13":8,
            "c14":8,
            "c15":8,
            "c16":8,
            "c17":8,
            "c18":8,
            "c19":8,
            "c20":8,
            "c21":8,
            "c23":8,
            "c24":8,
            "c25":8,
            "c27":8
        },
        {
            "type": "MP",
            "time": "18/05/2022, 15:15:15",
            "MP_name": "MP2",
            "SN": "EMSMP001",
            "plant_name": "plant1",
            "gatway_name": "gw3",
            "adress": 1,
            "baud_rate": 9600,
            "voltage": 230,
            "current": 10,
            "active_power": 2.3,
            "reactive_power": 0.01,
            "apparent_power": 2.3,
            "FP": 0.99,
            "frequency": 49.98
        },
        {
            "type": "TP",
            "time": "18/05/2022, 15:15:15",
            "TP_name": "TP2",
            "SN": "EMSMP002",
            "plant_name":"plant1",
            "gatway_name":"gw11",
            "adress": 1,
            "baud_rate":1,
            "UA":1,
            "UB":1,
            "UC":1,
            "UAB":1,
            "UBC":1,
            "UAC":1,
            "IA":1,
            "IB":20,
            "IC":43,
            "frequency":11,
            "Pa":88,
            "Pb":30,
            "Pc":23,
            "Pt":42,
            "Qa":21,
            "Qb":31,
            "Qc":49,
            "Qt":82,
            "Sa":63,
            "Sb":83,
            "Sc":10,
            "St":39,
            "FPa":54,
            "FPb":43,
            "FPc":34,
            "FPt":87,
            "THDV":56,
            "THDI":74,
            "max_demand":2,
            "count_E":8,
            "count_Er":55
        },
        {
            "type": "VFD",
            "time": "18/05/2022, 15:15:15",
            "vfd_name": "VFD2",
            "SN": "EMSMP002",
            "plant_name":"Greenaftech",
            "gatway_name":"gw1",
            "adress": 7,
            "baud_rate":1,
            "c00":8,
            "c01":36,
            "c02":44,
            "c03":15,
            "c04":28,
            "c06":41,
            "c07":56,
            "c12":10,
            "c13":11,
            "c14":7,
            "c15":893,
            "c16":12,
            "c17":60,
            "c18":46,
            "c19":83,
            "c20":47,
            "c21":83,
            "c23":20,
            "c24":32,
            "c25":89,
            "c27":58
        },
        {
            "type": "MP",
            "time": "18/05/2022, 15:15:15",
            "MP_name": "MP3",
            "SN": "EMSMP001",
            "plant_name": "ilisi",
            "gatway_name": "gw2",
            "adress": 1,
            "baud_rate": 9600,
            "voltage": 230,
            "current": 10,
            "active_power": 2.3,
            "reactive_power": 0.01,
            "apparent_power": 2.3,
            "FP": 0.99,
            "frequency": 49.98
        },
        {
            "type": "TP",
            "time": "18/05/2022, 15:15:15",
            "TP_name": "TR2",
            "SN": "EMSMP002",
            "plant_name":"ilisi",
            "gatway_name":"gw2",
            "adress": 1,
            "baud_rate":1,
            "UA":1,
            "UB":1,
            "UC":1,
            "UAB":1,
            "UBC":1,
            "UAC":1,
            "IA":1,
            "IB":20,
            "IC":43,
            "frequency":11,
            "Pa":88,
            "Pb":30,
            "Pc":23,
            "Pt":42,
            "Qa":21,
            "Qb":31,
            "Qc":49,
            "Qt":82,
            "Sa":63,
            "Sb":83,
            "Sc":10,
            "St":39,
            "FPa":54,
            "FPb":43,
            "FPc":34,
            "FPt":87,
            "THDV":56,
            "THDI":74,
            "max_demand":2,
            "count_E":8,
            "count_Er":55
        },
        {
            "type": "VFD",
            "time": "18/05/2022, 15:15:15",
            "vfd_name": "VFD3",
            "SN": "EMSMP002",
            "plant_name":"plant1",
            "gatway_name":"gw3",
            "adress": 7,
            "baud_rate":1,
            "c00":8,
            "c01":8,
            "c02":8,
            "c03":8,
            "c04":8,
            "c06":8,
            "c07":8,
            "c12":8,
            "c13":8,
            "c14":8,
            "c15":8,
            "c16":8,
            "c17":8,
            "c18":8,
            "c19":8,
            "c20":8,
            "c21":8,
            "c23":8,
            "c24":8,
            "c25":8,
            "c27":8
        }
        ]
    }
}

this is my models.py

class MP(models.Model):
    Monophase_Type=models.CharField(max_length=20,choices=infos_VFD)
    Monophase_Time= models.DateTimeField()
    
    MonoPhase_Name=models.CharField(max_length=20)
    Serial_Number=models.CharField(max_length=20)
    Plant_Name=models.ManyToManyField(Plant)
    Gateway_Name=models.ManyToManyField(Gateway)
    Adress=models.IntegerField()
    baud_rate=models.FloatField()
    Voltage=models.FloatField() 
    Current=models.FloatField()
    Active_Power= models.FloatField()
    Apparent_Power=models.FloatField()
    FP=models.FloatField()
    frenquency=models.FloatField()
    def __str__(self):
        return MonoPhase_Name
    
class TP(models.Model):
    Triphase_Type=models.CharField(max_length=20,choices=infos_VFD)
    Triphase_Time= models.DateTimeField()
    Triphase_Name=models.CharField(max_length=20)
    Serial_Number=models.CharField(max_length=20)
    Plant_Name=models.ManyToManyField(Plant)
    Gateway_Name=models.ManyToManyField(Gateway)
    Adress=models.IntegerField()
    Baud_Rate=models.FloatField()
    UA=models.FloatField()
    UB=models.FloatField()
    UC=models.FloatField()
    UAB=models.FloatField()
    UBC=models.FloatField()
    UAC=models.FloatField()
    IA=models.FloatField()
    IB=models.FloatField()
    IC=models.FloatField()
    frequency=models.FloatField()
    Pa=models.FloatField()
    Pb=models.FloatField()
    Pc=models.FloatField()
    Pt=models.FloatField()
    Qa=models.FloatField()
    Qb=models.FloatField()
    Qc=models.FloatField()
    Qt=models.FloatField()
    Sa=models.FloatField()
    Sb=models.FloatField()
    Sc=models.FloatField()
    St=models.FloatField()
    FPa=models.FloatField()
    FPb=models.FloatField()
    FPc=models.FloatField()
    FPt=models.FloatField()
    THDV=models.FloatField()
    THDI=models.FloatField()
    max_demand=models.FloatField()
    count_E=models.FloatField()
    count_Er=models.FloatField()
    def __str__(self):
        return Triphase_Name   


class api(models.Model):
    name=models.CharField(max_length=50)
    def __str__(self):
        return self.name
    
    

class vfdd(models.Model):
    VFDd_Typee=models.CharField(max_length=20,choices=infos_VFD)
    VFDd_Timee= models.DateTimeField()
    VFDd_Name=models.CharField(max_length=20)
    Serial_Number1=models.CharField(max_length=20)
    Plant_Namee=models.ManyToManyField(Plant)
    Gateway_Namee=models.ManyToManyField(Gateway)
    Adresss=models.IntegerField()
    baud_ratee=models.FloatField()
    c00=models.FloatField()
    c01=models.FloatField()
    c02=models.FloatField()
    c03=models.FloatField()
    c04=models.FloatField()
    c06=models.FloatField()
    c07=models.FloatField()
    c12=models.FloatField()
    c13=models.FloatField()
    c14=models.FloatField()
    c15=models.FloatField()
    c16=models.FloatField()
    c17=models.FloatField()
    c18=models.FloatField()
    c19=models.FloatField()
    c20=models.FloatField()
    c21=models.FloatField()
    c23=models.FloatField()
    c24=models.FloatField()
    c25=models.FloatField()
    c27=models.FloatField()
    def __str__(self):
        return self.VFDd_Name   

this is my serializers.py :

class MPSerializer(serializers.ModelSerializer):
    class Meta:
        model = MP 
        fields = '__all__'
        
class TPSerializer(serializers.ModelSerializer):
    class Meta:
        model = TP 
        fields = '__all__'
        
        
class VFDDSerializer(serializers.ModelSerializer):
    class Meta:
        model = vfdd
        fields = '__all__'    
        
        
class apiSerializer(serializers.ModelSerializer):
    device1=MPSerializer(many=True,read_only=True)
    device2=TPSerializer(many=True,read_only=True)
    device3=VFDDSerializer(many=True,read_only=True)                               
    class Meta:
        model = api
        fields = '__all__'  

and these are my views :

class apiListView(generics.ListCreateAPIView):
    serializer_class= apiSerializer
    queryset= api.objects.all()
    
    
class deviceListView(generics.ListCreateAPIView):
    serializer_class= MPSerializer
    queryset= MP.objects.all()    


         
     

CodePudding user response:

this is my views.py :

from . import serializers              
class deviceList(APIView):
   permission_classes = [] # if you have any permission classes.
  
   def get (self, request):
      mp = MP.objects.all()
      tp = TP.objects.all()
      vfd = vfddModel.objects.all()

      mp_data = serializers.MPSerializer(mp, many=True).data
      tp_data = serializers.TPSerializer(tp, many=True).data
      vffdd_data = serializers. VFDDSerializer(vfd, many=True).data

      nested_data = mp_data.extend(tp_data   vffdd_data)
      
      res = {
           "devices": nested_data
          }
      return Response(res)

this is my serializer.py :

from rest_framework import serializers
from django.contrib.auth.models import User
from .real_time_models import *           
class MPSerializer(serializers.ModelSerializer):
    type = serializers.SerializerMethodField(read_only=True)

    def get_type(self, obj):
        return "MP"

    class Meta:
        model = MP 
        fields = '__all__'
        
class TPSerializer(serializers.ModelSerializer):
    type = serializers.SerializerMethodField(read_only=True)

    def get_type(self, obj):
        return "TP"
    class Meta:
        model = TP 
        fields = '__all__'
        
        
class VFDDSerializer(serializers.ModelSerializer):
    type = serializers.SerializerMethodField(read_only=True)

    def get_type(self, obj):
        return "VFDD"

    class Meta:
        model = vfdd
        fields = '__all__'   

CodePudding user response:

So you can so something like this .

This is your serializers

class MPSerializer(serializers.ModelSerializer):
    type = serializers.SerializerMethodField(read_only=True)

    def get_type(self, obj):
        return "MP"

    class Meta:
        model = MP 
        fields = '__all__'
        
class TPSerializer(serializers.ModelSerializer):
    type = serializers.SerializerMethodField(read_only=True)

    def get_type(self, obj):
        return "TP"
    class Meta:
        model = TP 
        fields = '__all__'
        
        
class VFDDSerializer(serializers.ModelSerializer):
    type = serializers.SerializerMethodField(read_only=True)

    def get_type(self, obj):
        return "VFDD"

    class Meta:
        model = vfdd
        fields = '__all__'   

and you can create a view like this

from rest_framework.views import APIView
from . import real_time_serializers
from rest_framework.response import Response

Class deviceList(APIView):
   permission_classes = [] # if you have any permission classes.
  
   def get (self, request):
      mp = MpModel.objects.all()
      tp = TpModel.objects.all()
      vfdd = VfddModel.objects.all()

      mp_data = real_time_serializers.MPSerializer(mp, many=True).data
      tp_data = real_time_serializers.TPSerializer(tp, many=True).data
      vffdd_data = real_time_serializers. VFDDSerializer(vfdd, many=True).data

      nested_data = mp_data.extend(tp_data   vffdd_data)
      
      res = {
           "devices": nested_data
          }
      return Response(res)

Hope this will help you to solve your problem.

You can create a new view for the "PUT" & DELETE methods.

SO your urls can be like this.

path("some_name/<int:id>/<type>/", views.UpdateDeleteView..as_view())

and function can be like this.

from rest_framework.generics import RetrieveUpdateDestroyAPIView

Class UpdateDeleteView(RetrieveUpdateDestroyAPIView):
   permission_classes = [] # if you have any permission classes.
   lookup_field = "id"
   
   def get_queryset(self):
      if self.kwargs["type"] = "mp":
         return MpModel.objects.filter(id=self.kwargs['id']) 
      elif self.kwargs["type"] = "tp":
         return TpModel.objects.filter(id=self.kwargs['id'])
      elif self.kwargs["type"] = "vffdd_data":
         return VfddModel.objects.filter(id=self.kwargs['id'])  
     
  
  • Related