I have a basic Django application which uses sqlite as a backend on low-end hardware (eg. Raspberry Pi). I have the RPi collecting sensor data and logging it. I am trying to get the last process value, timestamp, and associated sensor name in an efficient way, but can't seem to figure it out with the Django ORM.
models.py
class Device(models.Model):
name = models.CharField(max_length=30)
class Log(models.Model):
timestamp = models.IntegerField()
value = models.FloatField()
device = models.ForeignKey(Device)
class Meta:
unique_together = ("timestamp", "device")
The following works, but is inefficient as it requires multiple SQL calls (one to start and then one for each device):
devices = Device.objects.all()
series = []
for device in devices:
log = Log.objects.filter(mapping_id=device.id).latest("timestamp")
series.append({"name": device.name,
"timestamp": log.timestamp,
"value": log.value})
I have searched around and it seems the annotate() method might be able to help, but I can't seem to figure out how to get the associated value along with the max timestamp:
Log.objects.values("device__name").annotate(timestamp=Max("timestamp")) # missing log value!
# or
Device.objects.annotate(timestamp=Max("log__timestamp")) # missing log value!