0
votes

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!

1
According to the docs passing field names to distinct() is only supported in PostgreSQL. Are you using PostgreSQL? - Ismail Badawi
What's more, it's a Django 1.4 feature. Are you running trunk or the alpha? - Alasdair
@isbadawi i'm running PGSQL... - Nuno Prata
@Alasdair I'm running trunk... Sorry, my mistake :(. Anyways, do you guys have any hint on how I can get that to work? It doens't forcefully has to use distinct(). - Nuno Prata
The thing is I want to return the whole object, not just some values - Nuno Prata

1 Answers

0
votes

Can you try this:

DeviceLocation.objects.filter(timestamp__range=(time_from, time_now)).order_by('device', '-timestamp').distinct('device')

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.