【发布时间】:2020-07-08 17:49:10
【问题描述】:
我有一些表 ports(switch_ip, slot_number, port_number, many, more, columns) 并希望使用 Django 实现以下 PostgreSQL 查询:
SELECT switch_ip, array_agg((slot_number, port_number, many, more, columns) ORDER BY slot_number, port_number) info
FROM ports
GROUP BY switch_ip
ORDER BY switch_ip
使用django.contrib.postgres.aggregates 这是我目前得到的结果:
Port.objects \
.values('switch_ip') \
.annotate(
info=ArrayAgg('slot_number', ordering=('slot_number', 'port_number'))
) \
.order_by('switch_ip')
我无法在ArrayAgg 中包含多于一列。 ArrayAgg(a, b, c)、ArrayAgg((a, b, c))、ArrayAgg([a, b, c]) 似乎都不起作用。解决方法可能涉及为每列单独的ArrayAggs,并且每列都具有相同的顺序。我会鄙视这一点,因为我有很多专栏。有没有更好的解决方法,可能更底层?
我怀疑这不是 ArrayAgg 本身的问题,而是一般的元组表达式。有没有办法在 Django 查询中使用元组?例如,对应的 Django 是什么:
SELECT switch_ip, (slot_number, port_number, many, more, columns) info
FROM ports
如果这在 Django 中还不能实现,那么实现起来有多可行?
【问题讨论】:
-
只是为了理解你的问题,为什么要在一个元组中返回这些值,而不是仅仅在python中构建元组?
-
@GrandPhuba 解决我最初的问题:不必使用多个
info1=ArrayAgg(a, ordering=o), info2=ArrayAgg(b, ordering=o), info3=ArrayAgg(c, ordering=o)进行注释,其中o每次都是相同的顺序。如果ArrayAgg可以在元组上工作,那么它只是类似于info=ArrayAgg((a, b, c), ordering=o)。因为我怀疑这不是ArrayAgg特有的问题,所以我将问题扩大到 Django 中的元组。
标签: django postgresql tuples aggregate-functions