我需要计算每个卖家 ID 的 周期中位数(参见下面的简化模型)。问题是我无法构建 ORM 查询。
模型class MyModel:
period = models.IntegerField(null=True, default=None)
seller_ids = ArrayField(models.IntegerField(), default=list)
aux = JSONField(default=dict)
询问queryset = (
MyModel.objects.filter(period=25)
.annotate(seller_id=Func(F("seller_ids"), function="unnest"))
.values("seller_id")
.annotate(
duration=Cast(KeyTextTransform("duration", "aux"), IntegerField()),
median=Func(
F("duration"),
function="percentile_cont",
template="%(function)s(0.5) WITHIN GROUP (ORDER BY %(expressions)s)",
),
)
.values("median", "seller_id")
)
ArrayField aggregation ( seller_id
) source
我认为我需要做的是以下几行select t.*, p_25, p_75
from t join
(select district,
percentile_cont(0.25) within group (order by sales) as p_25,
percentile_cont(0.75) within group (order by sales) as p_75
from t
group by district
) td
on t.district = td.district
above example source
Python 3.7.5、Django 2.2.8、Postgres 11.1
最佳答案
您可以创建 Median
类的 Aggregate
子类,就像 Ryan Murphy ( https://gist.github.com/rdmurphy/3f73c7b1826cacee34f6c2a855b12e2e ) 所做的那样。 Median
然后就像 Avg
一样工作:
from django.db.models import Aggregate, FloatField
class Median(Aggregate):
function = 'PERCENTILE_CONT'
name = 'median'
output_field = FloatField()
template = '%(function)s(0.5) WITHIN GROUP (ORDER BY %(expressions)s)'
然后找到一个字段的中位数使用
my_model_aggregate = MyModel.objects.all().aggregate(Median('period'))
然后可以作为
my_model_aggregate['period__median']
使用。
关于python - Django & Postgres - 百分位(中位数)和分组依据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59686945/