所以我有一个 SensorType
模型,其中有 SensorReading
的集合对象作为 sensorreading_set
的一部分(即传感器类型有许多传感器读数)。我想注释传感器类型,以便为我提供带有最大 ID 的传感器读数。也就是说:
sensor_types = SensorType.objects.annotate(
newest_reading_id=Max('sensorreading__id'))
这非常有效,但有一个问题。传感器读数有另一个外键,Device
。我真正想要的是给定设备的给定传感器类型的最高传感器读数ID。是否可以让注释引用传感器读数的子集,基本上相当于 SensorReading.objects.filter(device=device)
?
最佳答案
过滤与相关对象完美配合,注释与这些过滤器完美配合。您需要做的是:
from django.db.models import Max
SensorType.objects.filter(sensorreading__device=device) \
.annotate(newest_reading_id=Max('sensorreading__id'))
请注意,函数调用的顺序很重要。在 annotate
之前使用 filter
将仅对过滤后的集合进行注释,在 filter
之前使用 annotate
将在完整的集合上进行注释,然后过滤。另外,在过滤相关对象时,请记住 filter(sensorreading__x=x,sensorreading__y=y)
将过滤所有条件都为 true 的传感器读数,而 .filter(sensorreading__x=x) .filter(sensorreading__y=y)
将过滤满足这些条件之一的传感器读数。
关于python - 使用过滤后的相关对象集进行注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23376272/