I know this subject was discussed here, but I really can’t get this to work… 🙁
I have this DeviceLocation model:
class DeviceLocation(models.Model):
device = models.ForeignKey(Device, related_name='locations', null=True, on_delete=models.SET_NULL)
device_imei = models.CharField(max_length=20)
user = models.ForeignKey(User, related_name='device_locations', null=True, on_delete=models.SET_NULL)
user_username = models.CharField(max_length=30, null=True)
timestamp = models.DateTimeField()
latitude = models.FloatField()
longitude = models.FloatField()
accuracy = models.FloatField()
speed = models.FloatField()
I want to get the last location for each different device, in the last 5 min. So I tried this:
time_now = datetime.now()
time_from = time_now.replace(minute=time_now.minute - 5)
last_device_locations = DeviceLocation.objects.filter(timestamp__range=(time_from, time_now)).distinct('device')
The thing is, distinct is not working… Return multiple results for the same device.
I searched the site and found a work-around using values, even so I can’t do it:
DeviceLocation.objects.filter(timestamp__range=(time_from, time_now)).values(‘device’, ‘timestamp’).order_by(‘device’).distinct(‘device’)
but this still doesn’t work… 🙁
Any hints?
Thank you!
Can you try this:
I’m not sure, but it may be that the .values() call is interacting with the select distinct.
Also, you want to add
'-timestamp'to the .order_by() call, to make sure that you get the most recent location for each device.