Home > Back-end >  Nested Models in Serializer django
Nested Models in Serializer django

Time:08-29

I cannot get the last measurement for each device based on the device's ID from the measurement. If someone can advise me on how to implement this?

Models

class Devices(models.Model):
                        deviceid = models.AutoField(db_column='deviceId', primary_key=True)  # Field name made lowercase.
                        devicename = models.CharField(db_column='deviceName', unique=True, max_length=128)  # Field name made lowercase
                        devicestatus = models.IntegerField(db_column='deviceStatus')  # Field name made lowercase.
                    
                        Class Meta:
                            managed = False
                            db_table = 'devices'
                    
class Measurements(models.Model):
                        measurementid = models.AutoField(db_column='measurementId', primary_key=True)  # Field name made lowercase.
                        deviceid = models.ForeignKey(Devices,   models.DO_NOTHING, related_name="measurment_details", db_column='deviceId')  # Field name made lowercase.
                        measurement = models.CharField(max_length=64, blank=True, null=True)
                        
                    
                        class Meta:
                            managed = False
                            get_latest_by = 'measurementtime'
                            db_table = 'measurements'

Serializer

class MeasurmentsSerializer(serializers.ModelSerializer):
    class Meta:
      model = Measurements
      fields = ('measurementid','measurement')
   
class DeviceSerializer(serializers.ModelSerializer):
  latestmeasurment = serializers.SerializerMethodField()
  count = 0 
 
  
  def get_latestmeasurment(self, obj):
       qs = Measurements.objects.using('@@@').last()
       serializer = MeasurmentsSerializer(instance=qs, many=False)
       self.count = 1   self.count
       print(self.count , serializer.data )
       return serializer.data
 
  class Meta:
    model = Devices
    fields = ("devicename", 'latestmeasurment')

Views

class RetrieveAllDevicesView(viewsets.ModelViewSet):
  http_method_names = ['get']
  permission_classes = [permissions.IsAuthenticated]
  serializer_class = DeviceSerializer
  queryset = Devices.objects.using('@@@')

In serializer, you can see the count for primitive debug:

1 {'measurementid': 2942080, 'measurement': '35.0'}
2 {'measurementid': 2942080, 'measurement': '35.0'}
3 {'measurementid': 2942080, 'measurement': '35.0'}
4 {'measurementid': 2942080, 'measurement': '35.0'}
5 {'measurementid': 2942080, 'measurement': '35.0'}
6 {'measurementid': 2942080, 'measurement': '35.0'}
7 {'measurementid': 2942080, 'measurement': '35.0'}
8 {'measurementid': 2942080, 'measurement': '35.0'}
9 {'measurementid': 2942080, 'measurement': '35.0'}
10 {'measurementid': 2942080, 'measurement': '35.0'}

Response in JSON from view:

enter image description here

CodePudding user response:

def get_latestmeasurment(self, obj):
    device_measurements = obj.measurment_details.all()
    last_measurement = device_measurements.order_by('id').last()
    serializer = MeasurmentsSerializer(last_measurement)
    return serializer.data

you get all measurments for each device and after sorting it you'll get the last one as your last_measurment

  • Related