子查询 django 查询以从对象和 return 那些对象中获取最大的不同值

Subquery django query to get biggest disctint values from objects and return those objects

所以我有这个查询,我需要重新过滤以从不同的仪表 ID 中获取最大的 taken_at 字段值,但我无法获取 django orm's/sql 部分这个查询。

<QuerySet [<Reading: [127] meter installation: 29, type: 1, taken: 2019-10-07 16:06:48.101453+00:00 value: 78.0000, comment: , VAT: 22.00>, <Reading: [126] meter installation: 41, type: 2, taken: 2019-10-07 14:05:32.415905+00:00 value: 7.0000, comment: asdfe, VAT: None>, <Reading: [125] meter installation: 41, type: 2, taken: 2019-10-07 14:02:37.588983+00:00 value: 7.0000, comment: asdfe, VAT: None>, <Reading: [124] meter installation: 49, type: 2, taken: 2019-10-07 12:19:49.067398+00:00 value: 8.0000, comment: , VAT: 2.00>

此查询包含大量 Reading 对象,但我只需要从不同的仪表安装中获取最大的 taken_at 值,我已尝试制作注释然后再制作 distinct ,但它们没有一起实现,我我对 SQL 有点陌生,所以任何帮助都会很棒!

reading.py

class Reading(DateTrackedModel):
    meter_installation = models.ForeignKey(
        "MeterInstallation",
        on_delete=models.PROTECT,
        related_name="readings",
        null=False,
        blank=False,
        verbose_name=_("Meter Installation"),
    )
    value = models.DecimalField(
        decimal_places=4, max_digits=10, null=False, blank=False, default=0, verbose_name=_("Value")
    )
    price = models.DecimalField(
        decimal_places=4, max_digits=10, null=False, blank=False, default=0, verbose_name=_("Price")
    )
    reading_type = models.ForeignKey(
        "MeterType",
        on_delete=models.PROTECT,
        null=False,
        blank=False,
        related_name="readings",
        verbose_name=_("Reading type"),
    )
    comment = models.TextField(null=False, blank=True, verbose_name=_("Comment"))
    taken_at = models.DateTimeField(null=False, default=now, blank=False, verbose_name=_("Taken at"))
    VAT = models.DecimalField(decimal_places=2, max_digits=10, null=True, blank=True, verbose_name=_("VAT"))
    unit_name = models.CharField(max_length=100, null=False, blank=True, unique=False, verbose_name=_("Unit name"))
    unit_price = models.DecimalField(
        decimal_places=4, max_digits=10, null=False, blank=False, default=0.0, verbose_name=_("Unit price")
    )

仪表安装型号:

class MeterInstallation(ActiveAfterUntilModel, DateTrackedModel, MPTTModel, NamedModel):  # type: ignore
    meter_type = models.ForeignKey(
        MeterType,
        on_delete=models.PROTECT,
        null=False,
        blank=False,
        related_name="installations",
        verbose_name=_("Meter Installation type"),
    )
    parent = TreeForeignKey(
        "self", on_delete=models.CASCADE, null=True, blank=True, related_name="children", db_index=True
    )
    meter = models.ForeignKey(
        Meter, on_delete=models.PROTECT, related_name="installations", null=False, blank=False, verbose_name=_("Meter")
    )
    building = models.ForeignKey(
        Building,
        on_delete=models.PROTECT,
        related_name="meter_installations",
        null=True,
        blank=False,
        verbose_name=_("Building"),
    )
    places = models.ManyToManyField(Place, related_name="meter_installations", blank=False, verbose_name=_("Places"))
    initial_reading = models.DecimalField(
        decimal_places=4, max_digits=10, null=False, blank=False, default=0, verbose_name=_("Initial reading")
    )
    final_reading = models.DecimalField(
        decimal_places=4, max_digits=10, null=True, blank=True, verbose_name=_("Final reading")
    )

您的 Reading QuerySet 当前状态不是很清楚,但是可以在文档中找到 here 执行您想要的操作的一般方法。在你的情况下,它应该是这样的:

reading_qs.values('meter_installation').annotate(max_taken_at=models.Max('taken_at'))

更新:

所以从第一个 post 开始不是很清楚,但是您遇到了 问题。 (在你的情况下 n=1)

解决此特定版本问题的一种方法是通过 window query (如果您的数据库支持)。它应该是这样的:

    reading_qs.annotate(max_taken_at=Window(
        expression=Max('taken_at'),
        partition_by=F('meter_installation')
    )).filter(max_taken_at=F('taken_at'))

Update:这实际上是行不通的,因为Window注解是不可过滤的。我认为为了过滤 window 注释,你需要将它包装在 Subquery 中,但是对于 Subquery 你实际上没有义务使用 Window 函数,有另一种方法,这是我的下一个例子。

另一种方法是通过 subquery 它看起来像:

reading_qs.annotate(
    max_taken_at=Subquery(
            reading_qs.filter(meter_installation=OuterRef('meter_installation'))
            .values('meter_installation')
            .annotate(max_taken_at=Max('taken_at'))
            .values('max_taken_at')
    )
).filter(max_taken_at=F('taken_at'))

第三个解决方案,也就是 PostgreSQL 唯一的解决方案是:

reading_qs.order_by(
    'meter_installation', '-taken_at'
).distinct('meter_installation')