gpt4 book ai didi

python - Django -- 单个queryset(大数据集)中每个对象的最新相关状态记录

转载 作者:太空宇宙 更新时间:2023-11-03 11:49:06 33 4
gpt4 key购买 nike

[编辑:使用 Django 1.9 和 MySQL 5.6;没有 DISTINCT ON 关键字]

我有两个大致等同于以下的模型:

class Vehicle(models.Model):
vin = models.CharField(max_length=255)
... # lots more not-interesting fields


class Status(models.Model):
"""The status of a vehicle at a moment in time"""
vehicle = models.ForeignKey(Vehicle, related_name='status')
code = models.CharField(max_length=20)
time = models.DateTimeField()

class Meta:
order_by = ('time',)

如何使用单个查询 返回每辆车的当前状态?有数百种车辆和数十万条 Status 记录。

遍历每辆车并选择其最新状态对于车辆数​​量(数百)和状态(数十万)来说太慢了。

我尝试使用 .annotate() 和 .values() 来做到这一点;为什么这不起作用?我希望这会返回笛卡尔积车辆和状态表,然后过滤掉除最新状态之外的所有状态。

vehicles = Vehicle.objects.annotate(
status_time=F('status__time'),
status_time_latest=Max('status_time'),
status_code=F('status__code'),
).filter(
status_time=F('status_time_latest'),
).values()

相反,Django (1.9) 似乎只返回每辆车的第一个状态代码(按 ID 排序)。

这是 select_related() 的用途,还是最终会通过网络传输整个状态表?每次我需要运行这个查询时,它太大了,无法转储;我宁愿将处理卸载到数据库服务器。

最佳答案

您可以混合使用 order_bydistinct实现你想要的:

vehicles = Vehicle.objects
.annotate(status_time=F('status__time'), status_code=F('status__code'))
.order_by('id', '-status_time').distinct('id')

分解:

# first annotate all vehicle objects with all the statuses
vehicles = Vehicle.objects.annotate(status_time=F('status__time'), status_code=F('status__code'))

# order by id, and in decreasing order or status_time
vehicles = vehicles.order_by('id', '-status_time')

# get distinct using id, this will make sure that the first entry for
# each Vehicle is retained and since we ordered in decreasing order of
# status_time within each vehicle the first entry will have latest status
vehicles = vehicles.distinct('id')

关于python - Django -- 单个queryset(大数据集)中每个对象的最新相关状态记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36636550/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com