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!


-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/63483849-8057-431c-aa5b-3560ea17fdf9%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to