【发布时间】:2012-01-13 16:45:09
【问题描述】:
我知道这里讨论过这个主题,但我真的无法让它发挥作用...... :( 我有这个 DeviceLocation 模型:
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()
我想获取每个不同设备在过去 5 分钟内的最后位置。所以我尝试了这个:
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')
问题是,distinct 不起作用...为同一设备返回多个结果。 我搜索了该站点并找到了使用值的解决方法,即使这样我也做不到:
DeviceLocation.objects.filter(timestamp__range=(time_from, time_now)).values('device', 'timestamp').order_by('device').distinct('device')
但这仍然不起作用... :( 有什么提示吗?
谢谢!
【问题讨论】:
-
根据 the docs 将字段名称传递给
distinct()仅在 PostgreSQL 中支持。你在使用 PostgreSQL 吗? -
更重要的是,它是 Django 1.4 的一个特性。你运行的是trunk还是alpha?
-
@isbadawi 我正在运行 PGSQL...
-
@Alasdair 我正在运行主干...对不起,我的错误 :(。无论如何,你们对我如何让它工作有任何暗示吗?它没有强制使用不同的()。
-
问题是我想返回整个对象,而不仅仅是一些值